Chrome cannot convert date string to date in format YYYY/MM/DD PM hh:mm - google-chrome

I think Chrome is most flexible browser but it is not working in below case:
newrecorddate = "2015/10/20 PM 06:09"
var d = new Date(newrecorddate);
console.log("d="+d);
In IE11 the date (d) is returned successfully. In Chrome "Invalid Date" is returned. How can I workaround it?
UPDATE:
Dai's code actually solve the problem so it is marked as answer. Here is the code I use:
var r = /(\d{4})\/(\d{1,2})\/(\d{1,2}) (PM|AM) (\d{2})\:(\d{2})/;
if( newRecordDate.match( r ) ) {
var ymd = newRecordDate.split(" ")[0];
var tt = newRecordDate.split(" ")[1];
var tod = newRecordDate.split(" ")[2];
var d = new Date( ymd + " " + tod + " " + tt );
}
return d;

(Disclaimer: I worked on Chakra, Microsoft's JavaScript engine)
ECMAScript's specification does not list the formats that Date's constructor must successfully parse, in practice most implementations will generally successfully read almost every non-ambiguous format available, however the format you're using, YYYY/MM/dd tt HH:mm is not a format seen in reality (the tt is in the middle instead at the end). A good heuristic implementation might be able to guess it but it helps to not have to guess or depend on any feature support not present in the language's specification.
You'll have to parse the date yourself, reformat it, and pass that into Date's constructor, fortunately regex makes this easy:
var r = /(\d{4})/(\d{2})/(\d{2}) (PM|AM) (\d{2})\:(\d{2})/;
if( r.match( newRecordDate ) ) {
var ymd = newRecordDate.substr( 0, 10 ); // note substr instead of substring
var tt = newRecordDate.substr( 11, 2 );
var tod = newRecordDate.substr( 14, 5 );
var d = new Date( ymd + " " + tod + " " + tt );
}
That should work. Untested though.

Related

Comparing 2 strings from HTML file - Angular

I am using angular 7 and I would like to know how to compare two strings. In this case, each of my strings simulates one date, let's say "2019-12-26" and "2018-12-26".
In Javascript is pretty simple to compare them since I just need to use the operators:
console.log(today > "2018-12-06");
It is working how I supposed it was gonna work. It basically returns true. Nevertheless, I am trying to do exactly the same from my HTML file
<div *ngIf="today > example.endDate">
being today and 'example.endDate' two strings containing exactly the same strings that I used for the Javascript example, but it does not show any of them.
Is there any other way to make this comparison?
Regards,
Mario
UPDATE
I have had a second look at the problem and it seems that the comparison is not a problem, but the way of getting the variable is.
I get a variable in ngOnInit().
ngOnInit() {
this.getCurrentDate();
}
//Get current date
getCurrentDate() {
let aux = new Date();
//2 characteres
let dd = String(aux.getDate()).padStart(2, "0");
let mm = String(aux.getMonth() + 1).padStart(2, "0"); //January is 0!
let yyyy = aux.getFullYear();
let today = yyyy + "-" + mm + "-" + dd;
let other = "2019-01-31";
}
The problem is that I use this variable directly in my HTML how I previously showed. The error I get is the following:
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression
has changed after it was checked. Previous value: 'ngIf: undefined'.
Current value: 'ngIf: true'.
So the problem is that I am using a variable in the HTML file before getting the value. Or at least it is what I understand
To check this error I have created a Stackblitz representation. On it, I have created two examples:
Variables not on ngOnInit()
Variables in ngOnInit()
https://stackblitz.com/edit/angular-jjgsmq?file=src%2Fapp%2Fhello.component.ts
the most simple solution is just to
and are you sure that ngOnInit is the right LifeCycle hook for you?
I would try ngAfterContentInit() if the component is "heavy" to render other wise ngAfterViewInit() would have been my choice
<div *ngIf="IsTodayBigger()">
ngOnInit() {
this.getCurrentDate();
}
IsTodayBigger(): boolean {
today=this.getCurrentDate()
exampleEndDate= example.endDate;//use binding or ViewChild if needed
return today&&exampleEndDate&& today> example.endDate
}
//Get current date
getCurrentDate() {
let aux = new Date();
//2 characteres
let dd = String(aux.getDate()).padStart(2, "0");
let mm = String(aux.getMonth() + 1).padStart(2, "0"); //January is 0!
let yyyy = aux.getFullYear();
today = yyyy + "-" + mm + "-" + dd;
let other = "2019-01-31";
}

Node js and mysql date [duplicate]

How do I format a Date object to a string?
If you need slightly less control over formatting than the currently accepted answer, Date#toLocaleDateString can be used to create standard locale-specific renderings. The locale and options arguments let applications specify the language whose formatting conventions should be used, and allow some customization of the rendering.
Options key examples:
day:
The representation of the day.
Possible values are "numeric", "2-digit".
weekday:
The representation of the weekday.
Possible values are "narrow", "short", "long".
year:
The representation of the year.
Possible values are "numeric", "2-digit".
month:
The representation of the month.
Possible values are "numeric", "2-digit", "narrow", "short", "long".
hour:
The representation of the hour.
Possible values are "numeric", "2-digit".
minute:
The representation of the minute.
Possible values are "numeric", "2-digit".
second:
The representation of the second.
Possible values are "numeric", 2-digit".
All these keys are optional. You can change the number of options values based on your requirements, and this will also reflect the presence of each date time term.
Note: If you would only like to configure the content options, but still use the current locale, passing null for the first parameter will cause an error. Use undefined instead.
For different languages:
"en-US": For American English
"en-GB": For British English
"hi-IN": For Hindi
"ja-JP": For Japanese
You can use more language options.
For example
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today = new Date();
console.log(today.toLocaleDateString("en-US")); // 9/17/2016
console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016
console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016
You can also use the toLocaleString() method for the same purpose. The only difference is this function provides the time when you don't pass any options.
// Example
9/17/2016, 1:21:34 PM
References:
toLocaleString()
toLocaleDateString()
For custom-delimited date formats, you have to pull out the date (or time)
components from a DateTimeFormat object (which is part of the
ECMAScript Internationalization API), and then manually create a string
with the delimiters you want.
To do this, you can use DateTimeFormat#formatToParts. You could
destructure the array, but that is not ideal, as the array output depends on the
locale:
{ // example 1
let f = new Intl.DateTimeFormat('en');
let a = f.formatToParts();
console.log(a);
}
{ // example 2
let f = new Intl.DateTimeFormat('hi');
let a = f.formatToParts();
console.log(a);
}
Better would be to map a format array to resultant strings:
function join(t, a, s) {
function format(m) {
let f = new Intl.DateTimeFormat('en', m);
return f.format(t);
}
return a.map(format).join(s);
}
let a = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}];
let s = join(new Date, a, '-');
console.log(s);
You can also pull out the parts of a DateTimeFormat one-by-one using
DateTimeFormat#format, but note that when using this method, as of March
2020, there is a bug in the ECMAScript implementation when it comes to
leading zeros on minutes and seconds (this bug is circumvented by the approach
above).
let d = new Date(2010, 7, 5);
let ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
let mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d);
let da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
console.log(`${da}-${mo}-${ye}`);
When working with dates and times, it is usually worth using a library (eg. luxon, date-fns, moment.js is not recommended for new projects) because of the many hidden complexities of the field.
Note that the ECMAScript Internationalization API, used in the solutions above
is not supported in IE10 (0.03% global browser market share in Feb
2020).
If you need to quickly format your date using plain JavaScript, use getDate, getMonth + 1, getFullYear, getHours and getMinutes:
var d = new Date();
var datestring = d.getDate() + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " +
d.getHours() + ":" + d.getMinutes();
// 16-5-2015 9:50
Or, if you need it to be padded with zeros:
var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);
// 16-05-2015 09:50
Use the date.format library:
var dateFormat = require('dateformat');
var now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
returns:
Saturday, June 9th, 2007, 5:46:21 PM
dateformat on npm
http://jsfiddle.net/phZr7/1/
Well, what I wanted was to convert today's date to a MySQL friendly date string like 2012-06-23, and to use that string as a parameter in one of my queries. The simple solution I've found is this:
var today = new Date().toISOString().slice(0, 10);
Keep in mind that the above solution does not take into account your timezone offset.
You might consider using this function instead:
function toJSONLocal (date) {
var local = new Date(date);
local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return local.toJSON().slice(0, 10);
}
This will give you the correct date in case you are executing this code around the start/end of the day.
var date = new Date();
function toLocal(date) {
var local = new Date(date);
local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return local.toJSON();
}
function toJSONLocal(date) {
var local = new Date(date);
local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return local.toJSON().slice(0, 10);
}
// check out your devtools console
console.log(date.toJSON());
console.log(date.toISOString());
console.log(toLocal(date));
console.log(toJSONLocal(date));
Date.toISOString
Date.toJSON
String.slice
External example
Custom formatting function:
For fixed formats, a simple function make the job. The following example generates the international format YYYY-MM-DD:
function dateToYMD(date) {
var d = date.getDate();
var m = date.getMonth() + 1; //Month from 0 to 11
var y = date.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}
console.log(dateToYMD(new Date(2017,10,5))); // Nov 5
The OP format may be generated like:
function dateToYMD(date) {
var strArray=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var d = date.getDate();
var m = strArray[date.getMonth()];
var y = date.getFullYear();
return '' + (d <= 9 ? '0' + d : d) + '-' + m + '-' + y;
}
console.log(dateToYMD(new Date(2017,10,5))); // Nov 5
Note: It is, however, usually not a good idea to extend the JavaScript standard libraries (e.g. by adding this function to the prototype of Date).
A more advanced function could generate configurable output based on a format parameter.
If to write a formatting function is too long, there are plenty of libraries around which does it. Some other answers already enumerate them. But increasing dependencies also has it counter-part.
Standard ECMAScript formatting functions:
Since more recent versions of ECMAScript, the Date class has some specific formatting functions:
toDateString: Implementation dependent, show only the date.
https://262.ecma-international.org/#sec-date.prototype.todatestring
new Date().toDateString(); // e.g. "Fri Nov 11 2016"
toISOString: Show ISO 8601 date and time.
https://262.ecma-international.org/#sec-date.prototype.toisostring
new Date().toISOString(); // e.g. "2016-11-21T08:00:00.000Z"
toJSON: Stringifier for JSON.
https://262.ecma-international.org/#sec-date.prototype.tojson
new Date().toJSON(); // e.g. "2016-11-21T08:00:00.000Z"
toLocaleDateString: Implementation dependent, a date in locale format.
https://262.ecma-international.org/#sec-date.prototype.tolocaledatestring
new Date().toLocaleDateString(); // e.g. "21/11/2016"
toLocaleString: Implementation dependent, a date&time in locale format.
https://262.ecma-international.org/#sec-date.prototype.tolocalestring
new Date().toLocaleString(); // e.g. "21/11/2016, 08:00:00 AM"
toLocaleTimeString: Implementation dependent, a time in locale format.
https://262.ecma-international.org/#sec-date.prototype.tolocaletimestring
new Date().toLocaleTimeString(); // e.g. "08:00:00 AM"
toString: Generic toString for Date.
https://262.ecma-international.org/#sec-date.prototype.tostring
new Date().toString(); // e.g. "Fri Nov 21 2016 08:00:00 GMT+0100 (W. Europe Standard Time)"
Note: it is possible to generate custom output out of those formatting >
new Date().toISOString().slice(0,10); //return YYYY-MM-DD
Examples snippets:
console.log("1) "+ new Date().toDateString());
console.log("2) "+ new Date().toISOString());
console.log("3) "+ new Date().toJSON());
console.log("4) "+ new Date().toLocaleDateString());
console.log("5) "+ new Date().toLocaleString());
console.log("6) "+ new Date().toLocaleTimeString());
console.log("7) "+ new Date().toString());
console.log("8) "+ new Date().toISOString().slice(0,10));
Specifying the locale for standard functions:
Some of the standard functions listed above are dependent on the locale:
toLocaleDateString()
toLocaleTimeString()
toLocalString()
This is because different cultures make uses of different formats, and express their date or time in different ways.
The function by default will return the format configured on the device it runs, but this can be specified by setting the arguments (ECMA-402).
toLocaleDateString([locales[, options]])
toLocaleTimeString([locales[, options]])
toLocaleString([locales[, options]])
//e.g. toLocaleDateString('ko-KR');
The option second parameter, allow for configuring more specific format inside the selected locale. For instance, the month can be show as full-text or abreviation.
toLocaleString('en-GB', { month: 'short' })
toLocaleString('en-GB', { month: 'long' })
Examples snippets:
console.log("1) "+ new Date().toLocaleString('en-US'));
console.log("2) "+ new Date().toLocaleString('ko-KR'));
console.log("3) "+ new Date().toLocaleString('de-CH'));
console.log("4) "+ new Date().toLocaleString('en-GB', { hour12: false }));
console.log("5) "+ new Date().toLocaleString('en-GB', { hour12: true }));
Some good practices regarding locales:
Most people don't like their dates to appear in a foreigner format, consequently, keep the default locale whenever possible (over setting 'en-US' everywhere).
Implementing conversion from/to UTC can be challenging (considering DST, time-zone not multiple of 1 hour, etc.). Use a well-tested library when possible.
Don't assume the locale correlate to a country: several countries have many of them (Canada, India, etc.)
Avoid detecting the locale through non-standard ways. Here you can read about the multiple pitfalls: detecting the keyboard layout, detecting the locale by the geographic location, etc..
If you are already using jQuery UI in your project you could do it this way:
var formatted = $.datepicker.formatDate("M d, yy", new Date("2014-07-08T09:02:21.377"));
// formatted will be 'Jul 8, 2014'
Some datepicker date format options to play with are available here.
Note (2022-10): toLocaleFormat has been deprecated for some time and was removed from Firefox as of version 58. See toLocaleFormat
I think you can just use the non-standard Date method toLocaleFormat(formatString)
formatString: A format string in the same format expected by the strftime() function in C.
var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011
References:
toLocaleFormat
strftime
Plain JavaScript is the best pick for small onetimers.
On the other hand, if you need more date stuff, MomentJS is a great solution.
For example:
moment().format('YYYY-MM-DD HH:m:s'); // now() -> 2015-03-24 14:32:20
moment("20111031", "YYYYMMDD").fromNow(); // 3 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow(); // 11 hours ago
moment().endOf('day').fromNow(); // in 13 hours
In modern browsers (*), you can just do this:
var today = new Date().toLocaleDateString('en-GB', {
day : 'numeric',
month : 'short',
year : 'numeric'
}).split(' ').join('-');
Output if executed today (january 24ᵗʰ, 2016):
'24-Jan-2016'
(*) According to MDN, "modern browsers" means Chrome 24+, Firefox 29+, Internet Explorer 11, Edge 12+, Opera 15+ & Safari nightly build.
Requested format in one line - no libraries and no Date methods, just regex:
var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')
In my testing, this works reliably in the major browsers (Chrome, Safari, Firefox and IE.) As #RobG pointed out, the output of Date.prototype.toString() is implementation-dependent, so for international or non-browser implementations, just test the output to be sure it works right in your JavaScript engine. You can even add some code to test the string output and make sure it's matching what you expect before you do the regex replace.
Packaged Solution: Luxon or date-fns
If you want to use a one solution to fit all, I recommend using date-fns or Luxon.
Luxon is hosted on the Moment.js website and developed by a Moment.js developer because Moment.js has limitations that the developer wanted to address but couldn't.
To install:
npm install luxon or yarn add luxon (visit link for other installation methods)
Example:
luxon.DateTime.fromISO('2010-08-10').toFormat('yyyy-LLL-dd');
Yields:
10-Aug-2010
Manual Solution
Using similar formatting as Moment.js, Class DateTimeFormatter (Java), and Class SimpleDateFormat (Java), I implemented a comprehensive solution formatDate(date, patternStr) where the code is easy to read and modify. You can display date, time, AM/PM, etc. See code for more examples.
Example:
formatDate(new Date(), 'EEEE, MMMM d, yyyy HH:mm:ss:S')
(formatDate is implemented in the code snippet below)
Yields:
Friday, October 12, 2018 18:11:23:445
Try the code out by clicking "Run code snippet."
Date and Time Patterns
yy = 2-digit year; yyyy = full year
M = digit month; MM = 2-digit month; MMM = short month name; MMMM = full month name
EEEE = full weekday name; EEE = short weekday name
d = digit day; dd = 2-digit day
h = hours am/pm; hh = 2-digit hours am/pm; H = hours; HH = 2-digit hours
m = minutes; mm = 2-digit minutes; aaa = AM/PM
s = seconds; ss = 2-digit seconds
S = miliseconds
var monthNames = [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
];
var dayOfWeekNames = [
"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"
];
function formatDate(date, patternStr){
if (!patternStr) {
patternStr = 'M/d/yyyy';
}
var day = date.getDate(),
month = date.getMonth(),
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds(),
miliseconds = date.getMilliseconds(),
h = hour % 12,
hh = twoDigitPad(h),
HH = twoDigitPad(hour),
mm = twoDigitPad(minute),
ss = twoDigitPad(second),
aaa = hour < 12 ? 'AM' : 'PM',
EEEE = dayOfWeekNames[date.getDay()],
EEE = EEEE.substr(0, 3),
dd = twoDigitPad(day),
M = month + 1,
MM = twoDigitPad(M),
MMMM = monthNames[month],
MMM = MMMM.substr(0, 3),
yyyy = year + "",
yy = yyyy.substr(2, 2)
;
// checks to see if month name will be used
patternStr = patternStr
.replace('hh', hh).replace('h', h)
.replace('HH', HH).replace('H', hour)
.replace('mm', mm).replace('m', minute)
.replace('ss', ss).replace('s', second)
.replace('S', miliseconds)
.replace('dd', dd).replace('d', day)
.replace('EEEE', EEEE).replace('EEE', EEE)
.replace('yyyy', yyyy)
.replace('yy', yy)
.replace('aaa', aaa);
if (patternStr.indexOf('MMM') > -1) {
patternStr = patternStr
.replace('MMMM', MMMM)
.replace('MMM', MMM);
}
else {
patternStr = patternStr
.replace('MM', MM)
.replace('M', M);
}
return patternStr;
}
function twoDigitPad(num) {
return num < 10 ? "0" + num : num;
}
console.log(formatDate(new Date()));
console.log(formatDate(new Date(), 'dd-MMM-yyyy')); //OP's request
console.log(formatDate(new Date(), 'EEEE, MMMM d, yyyy HH:mm:ss.S aaa'));
console.log(formatDate(new Date(), 'EEE, MMM d, yyyy HH:mm'));
console.log(formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss.S'));
console.log(formatDate(new Date(), 'M/dd/yyyy h:mmaaa'));
Thank you #Gerry for bringing up Luxon.
#Sébastien -- alternative all browser support
new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');
Documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
High-order tagged template literal example based on Date.toLocaleDateString:
const date = new Date(Date.UTC(2020, 4, 2, 3, 23, 16, 738));
const fmt = (dt, lc = "en-US") => (str, ...expr) =>
str.map((str, i) => str + (expr[i]?dt.toLocaleDateString(lc, expr[i]) :'')).join('')
console.log(fmt(date)`${{year: 'numeric'}}-${{month: '2-digit'}}-${{day: '2-digit'}}`);
// expected output: "2020-05-02"
OK, we have got something called Intl which is very useful for formatting a date in JavaScript these days:
Your date as below:
var date = '10/8/2010';
And you change to Date by using new Date() like below:
date = new Date(date);
And now you can format it any way you like using a list of locales like below:
date = new Intl.DateTimeFormat('en-AU').format(date); // Australian date format: "8/10/2010"
date = new Intl.DateTimeFormat('en-US').format(date); // USA date format: "10/8/2010"
date = new Intl.DateTimeFormat('ar-EG').format(date); // Arabic date format: "٨‏/١٠‏/٢٠١٠"
If you exactly want the format you mentioned above, you can do:
date = new Date(Date.UTC(2010, 7, 10, 0, 0, 0));
var options = {year: "numeric", month: "short", day: "numeric"};
date = new Intl.DateTimeFormat("en-AU", options).format(date).replace(/\s/g, '-');
And the result is going to be:
"10-Aug-2010"
For more see the Intl API and Intl.DateTimeFormat documentation.
Using an ECMAScript Edition 6 (ES6/ES2015) string template:
let d = new Date();
let formatted = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
If you need to change the delimiters:
const delimiter = '/';
let formatted = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join(delimiter);
The Date constructor (and Date.parse()) only accepts one format as a parameter when constructing a date and that is ISO 8601:
// new Date('YYYY-MM-DDTHH:mm:ss.sssZ')
const date = new Date('2017-08-15')
But parsing a from a string is strongly discouraged (MDN recommends against creating date with date strings) due to browser differences and inconsistencies.
The recommended alternative would be building your Date instance directly from the numeric data like this:
new Date(2017, 7, 15) // Month is zero-indexed
That is parsing. Now, to format your date to the string you desire you have several options that are native of the Date object (although I believe none is compliant to the format you require):
date.toString() // 'Wed Jan 23 2019 17:23:42 GMT+0800 (Singapore Standard Time)'
date.toDateString() // 'Wed Jan 23 2019'
date.toLocaleString() // '23/01/2019, 17:23:42'
date.toGMTString() // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toUTCString() // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toISOString() // '2019-01-23T09:23:42.079Z'
For other formatting options I'm afraid you'll have to turn to libraries such as Moment.js, day.js and the like.
Credit to Zell Liew from this article for the date formatting tips.
Here's is some code I just wrote to handle the date formatting for a project I'm working on. It mimics the PHP date formatting functionality to suit my needs. Feel free to use it, it's just extending the already existing Date() object. This may not be the most elegant solution but it's working for my needs.
var d = new Date();
d_string = d.format("m/d/Y h:i:s");
/**************************************
* Date class extension
*
*/
// Provide month names
Date.prototype.getMonthName = function(){
var month_names = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
return month_names[this.getMonth()];
}
// Provide month abbreviation
Date.prototype.getMonthAbbr = function(){
var month_abbrs = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
return month_abbrs[this.getMonth()];
}
// Provide full day of week name
Date.prototype.getDayFull = function(){
var days_full = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
return days_full[this.getDay()];
};
// Provide full day of week name
Date.prototype.getDayAbbr = function(){
var days_abbr = [
'Sun',
'Mon',
'Tue',
'Wed',
'Thur',
'Fri',
'Sat'
];
return days_abbr[this.getDay()];
};
// Provide the day of year 1-365
Date.prototype.getDayOfYear = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((this - onejan) / 86400000);
};
// Provide the day suffix (st,nd,rd,th)
Date.prototype.getDaySuffix = function() {
var d = this.getDate();
var sfx = ["th","st","nd","rd"];
var val = d%100;
return (sfx[(val-20)%10] || sfx[val] || sfx[0]);
};
// Provide Week of Year
Date.prototype.getWeekOfYear = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
// Provide if it is a leap year or not
Date.prototype.isLeapYear = function(){
var yr = this.getFullYear();
if ((parseInt(yr)%4) == 0){
if (parseInt(yr)%100 == 0){
if (parseInt(yr)%400 != 0){
return false;
}
if (parseInt(yr)%400 == 0){
return true;
}
}
if (parseInt(yr)%100 != 0){
return true;
}
}
if ((parseInt(yr)%4) != 0){
return false;
}
};
// Provide Number of Days in a given month
Date.prototype.getMonthDayCount = function() {
var month_day_counts = [
31,
this.isLeapYear() ? 29 : 28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
];
return month_day_counts[this.getMonth()];
}
// format provided date into this.format format
Date.prototype.format = function(dateFormat){
// break apart format string into array of characters
dateFormat = dateFormat.split("");
var date = this.getDate(),
month = this.getMonth(),
hours = this.getHours(),
minutes = this.getMinutes(),
seconds = this.getSeconds();
// get all date properties ( based on PHP date object functionality )
var date_props = {
d: date < 10 ? '0'+date : date,
D: this.getDayAbbr(),
j: this.getDate(),
l: this.getDayFull(),
S: this.getDaySuffix(),
w: this.getDay(),
z: this.getDayOfYear(),
W: this.getWeekOfYear(),
F: this.getMonthName(),
m: month < 10 ? '0'+(month+1) : month+1,
M: this.getMonthAbbr(),
n: month+1,
t: this.getMonthDayCount(),
L: this.isLeapYear() ? '1' : '0',
Y: this.getFullYear(),
y: this.getFullYear()+''.substring(2,4),
a: hours > 12 ? 'pm' : 'am',
A: hours > 12 ? 'PM' : 'AM',
g: hours % 12 > 0 ? hours % 12 : 12,
G: hours > 0 ? hours : "12",
h: hours % 12 > 0 ? hours % 12 : 12,
H: hours,
i: minutes < 10 ? '0' + minutes : minutes,
s: seconds < 10 ? '0' + seconds : seconds
};
// loop through format array of characters and add matching data else add the format character (:,/, etc.)
var date_string = "";
for(var i=0;i<dateFormat.length;i++){
var f = dateFormat[i];
if(f.match(/[a-zA-Z]/g)){
date_string += date_props[f] ? date_props[f] : '';
} else {
date_string += f;
}
}
return date_string;
};
/*
*
* END - Date class extension
*
************************************/
This may help with the problem:
var d = new Date();
var options = {
day: 'numeric',
month: 'long',
year: 'numeric'
};
console.log(d.toLocaleDateString('en-ZA', options));
A useful and flexible way for formatting the DateTimes in JavaScript is Intl.DateTimeFormat:
var date = new Date();
var options = { year: 'numeric', month: 'short', day: '2-digit'};
var _resultDate = new Intl.DateTimeFormat('en-GB', options).format(date);
// The _resultDate is: "12 Oct 2017"
// Replace all spaces with - and then log it.
console.log(_resultDate.replace(/ /g,'-'));
Result Is: "12-Oct-2017"
The date and time formats can be customized using the options argument.
The Intl.DateTimeFormat object is a constructor for objects that enable language sensitive date and time formatting.
Syntax
new Intl.DateTimeFormat([locales[, options]])
Intl.DateTimeFormat.call(this[, locales[, options]])
Parameters
locales
Optional. A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the Intl page. The following Unicode extension keys are allowed:
nu
Numbering system. Possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt".
ca
Calendar. Possible values include: "buddhist", "chinese", "coptic", "ethioaa", "ethiopic", "gregory", "hebrew", "indian", "islamic", "islamicc", "iso8601", "japanese", "persian", "roc".
Options
Optional. An object with some or all of the following properties:
localeMatcher
The locale matching algorithm to use. Possible values are "lookup" and "best fit"; the default is "best fit". For information about this option, see the Intl page.
timeZone
The time zone to use. The only value implementations must recognize is "UTC"; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the IANA time zone database, such as "Asia/Shanghai", "Asia/Kolkata", "America/New_York".
hour12
Whether to use 12-hour time (as opposed to 24-hour time). Possible values are true and false; the default is locale dependent.
formatMatcher
The format matching algorithm to use. Possible values are "basic" and "best fit"; the default is "best fit". See the following paragraphs for information about the use of this property.
The following properties describe the date-time components to use in formatted output and their desired representations. Implementations are required to support at least the following subsets:
weekday, year, month, day, hour, minute, second
weekday, year, month, day
year, month, day
year, month
month, day
hour, minute, second
hour, minute
Implementations may support other subsets, and requests will be negotiated against all available subset-representation combinations to find the best match. Two algorithms are available for this negotiation and selected by the formatMatcher property: A fully specified "basic" algorithm and an implementation dependent "best fit" algorithm.
weekday
The representation of the weekday. Possible values are "narrow", "short", "long".
era
The representation of the era. Possible values are "narrow", "short", "long".
year
The representation of the year. Possible values are "numeric", "2-digit".
month
The representation of the month. Possible values are "numeric", "2-digit", "narrow", "short", "long".
day
The representation of the day. Possible values are "numeric", "2-digit".
hour
The representation of the hour. Possible values are "numeric", "2-digit".
minute
The representation of the minute. Possible values are "numeric", "2-digit".
second
The representation of the second. Possible values are "numeric", "2-digit".
timeZoneName
The representation of the time zone name. Possible values are "short", "long".
The default value for each date-time component property is undefined, but if all component properties are undefined, then the year, month and day are assumed to be "numeric".
Check Online
More Details
A JavaScript solution without using any external libraries:
var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate() + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)
new Date().toLocaleDateString()
// "3/21/2018"
More documentation at developer.mozilla.org
We have lots of solutions for this, but I think the best of them is Moment.js. So I personally suggest to use Moment.js for date and time operations.
console.log(moment().format('DD-MMM-YYYY'));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
If you are using jQuery UI in your code, there is an inbuilt function called formatDate(). I am using it this way to format today's date:
var testdate = Date();
testdate = $.datepicker.formatDate( "d-M-yy",new Date(testdate));
alert(testdate);
You can see many other examples of formatting date in the jQuery UI documentation.
This is how I implemented for my npm plugins
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var Days = [
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
];
var formatDate = function(dt,format){
format = format.replace('ss', pad(dt.getSeconds(),2));
format = format.replace('s', dt.getSeconds());
format = format.replace('dd', pad(dt.getDate(),2));
format = format.replace('d', dt.getDate());
format = format.replace('mm', pad(dt.getMinutes(),2));
format = format.replace('m', dt.getMinutes());
format = format.replace('MMMM', monthNames[dt.getMonth()]);
format = format.replace('MMM', monthNames[dt.getMonth()].substring(0,3));
format = format.replace('MM', pad(dt.getMonth()+1,2));
format = format.replace(/M(?![ao])/, dt.getMonth()+1);
format = format.replace('DD', Days[dt.getDay()]);
format = format.replace(/D(?!e)/, Days[dt.getDay()].substring(0,3));
format = format.replace('yyyy', dt.getFullYear());
format = format.replace('YYYY', dt.getFullYear());
format = format.replace('yy', (dt.getFullYear()+"").substring(2));
format = format.replace('YY', (dt.getFullYear()+"").substring(2));
format = format.replace('HH', pad(dt.getHours(),2));
format = format.replace('H', dt.getHours());
return format;
}
pad = function(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
You should have a look at DayJs It's a remake of momentJs but modular architecture oriented so lighter.
Fast 2kB alternative to Moment.js with the same modern API
Day.js is a minimalist JavaScript library that parses, validates, manipulates, and displays dates and times for modern browsers with a largely Moment.js-compatible API. If you use Moment.js, you already know how to use Day.js.
var date = Date.now();
const formatedDate = dayjs(date).format("YYYY-MM-DD")
console.log(formatedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.16/dayjs.min.js" crossorigin="anonymous"></script>
var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();
Inspired by JD Smith's marvellous regular expression solution, I suddenly had this head-splitting idea:
var D = Date().toString().split(" ");
console.log(D[2] + "-" + D[1] + "-" + D[3]);
For any one looking for a really simple ES6 solution to copy, paste and adopt:
const dateToString = d => `${d.getFullYear()}-${('00' + (d.getMonth() + 1)).slice(-2)}-${('00' + d.getDate()).slice(-2)}`
// how to use:
const myDate = new Date(Date.parse('04 Dec 1995 00:12:00 GMT'))
console.log(dateToString(myDate)) // 1995-12-04
As of 2019, it looks like you can get toLocaleDateString to return only certain parts and then you can join them as you wish:
var date = new Date();
console.log(date.toLocaleDateString("en-US", { day: 'numeric' })
+ "-"+ date.toLocaleDateString("en-US", { month: 'short' })
+ "-" + date.toLocaleDateString("en-US", { year: 'numeric' }) );
> 16-Nov-2019
console.log(date.toLocaleDateString("en-US", { month: 'long' })
+ " " + date.toLocaleDateString("en-US", { day: 'numeric' })
+ ", " + date.toLocaleDateString("en-US", { year: 'numeric' }) );
> November 16, 2019
It works same in Internet Explorer 11, Firefox, and Chrome (Chrome 80.x shows 12 hours format when en-UK selected).
const d = new Date('2010/08/05 23:45') // 26.3.2020
const dtfUK = new Intl.DateTimeFormat('UK', { year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit',minute: '2-digit', second: '2-digit' }); //
const dtfUS = new Intl.DateTimeFormat('en', { year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit',minute: '2-digit', second: '2-digit' }); //
console.log(dtfUS.format(d)); // 08/05/2010 11:45:00 PM
console.log(dtfUK.format(d)); // 05.08.2010 23:45:00
/* node.js:
08/05/2010, 11:45:00 PM
2010-08-05 23:45:00
*/
What about something more general?
var d = new Date('2010-08-10T10:34:56.789Z');
var str = d.toDateString() + // Tue Aug 10 2010
' ' + d.toTimeString().split(' ')[0] + // 12:34:56, GMT+0x00 (GMT+0x:00)
' ' + (d.getMonth() + 101) + // 108
' ' + d.getMilliseconds(); // 789
console.log(str); // Tue Aug 10 2010 12:34:56 108 789
console.log(// $1 Tue $2 Aug $3 11 $4 2020 $5 12 $6 34 $7 56 $8 108 $9 789
str.replace(/(\S{3}) (\S{3}) (\d{1,2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) 1(\d{2}) (\d{1,3})/, '$3-$2-$4 $5:$6.$9 ($1)')
); // 10-Aug-2010 12:34.789 (Tue)
/*
$1: Tue Week Day string
$2: Aug Month short text
$3: 11 Day
$4: 2010 Year
$5: 12 Hour
$6: 34 Minute
$7: 56 Seconds
$8: 08 Month
$9: 789 Milliseconds
*/
Or for example 1-line IIFE "library" ;-)
console.log(
(function (frm, d) { return [d.toDateString(), d.toTimeString().split(' ')[0], (d.getMonth() + 101), d.getMilliseconds()].join(' ').replace(/(\S{3}) (\S{3}) (\d{1,2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) 1(\d{2}) (\d{1,3})/, frm); })
('$4/$8/$3 $5:$6 ($1)', new Date())
);
You can remove useless parts and / or change indexes if you do not need them.

Converting mysql date to js date works in chrome but not safari

I am using a pipe in angular2 to convert a mysql date to a js date format here is my code:
export class DateToIso {
transform(value) {
let date = new Date(value);
let str = (date.getMonth() + 1) + '.' + date.getDate() + '.' + date.getFullYear()
return str;
}
}
In HTML I use
{{ post[2] | dateToIso}}
to show the converted date. In Chrome I get the correct datetime but not in safari. It returns NaN.NaN.NaN.
I had a similar problem with the currency pipe and it was an internationalization issue. I wrote it up here http://blogs.msmvps.com/deborahk/angular-2-getting-started-problem-solver/
Install the international package: npm install intl#1.1.0 –save
Include the following in index.html:
(I'm using a touch device and the pasted code doesn't work. Please see the link)
I tried it #DeborahK but it didn`t work so I just took the Mysql date "String" and made substrings out of it and rearranged the substrings to a new string and returned it.
export class DateToIso {
transform(value, args) {
let month = value.substr(5,2);
let day = value.substr(8,2);
let timeThen = value.substr(11,5);
let newValue = day + "." + month + " um " + timeThen;
return newValue;
}
}
I believe this is not the best solution but it is working. Hope to get better solutions soon.

How to set input type date's default value to today?

Given an input element:
<input type="date" />
Is there any way to set the default value of the date field to today's date?
Like any HTML input field, the browser will leave the date element empty unless a default value is specified within the value attribute. Unfortunately, HTML5 doesn't provide a way of specifying 'today' in the HTMLInputElement.prototype.value.
One must instead explicitly provide a RFC3339 formatted date (YYYY-MM-DD). For example:
element.value = "2011-09-29"
Use HTMLInputElement.prototype.valueAsDate:
document.getElementById('datePicker').valueAsDate = new Date();
The JavaScript Date object provides enough built-in support for the required format to avoid doing it manually:
Add this for correct timezone support:
Date.prototype.toDateInputValue = (function() {
var local = new Date(this);
local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
return local.toJSON().slice(0,10);
});
jQuery:
$(document).ready( function() {
$('#datePicker').val(new Date().toDateInputValue());
});​
Pure JS:
document.getElementById('datePicker').value = new Date().toDateInputValue();
This relies upon PHP:
<input type="date" value="<?php echo date('Y-m-d'); ?>" />
You could fill the default value through JavaScript as seen here:
http://jsfiddle.net/7LXPq/
$(document).ready( function() {
var now = new Date();
var month = (now.getMonth() + 1);
var day = now.getDate();
if (month < 10)
month = "0" + month;
if (day < 10)
day = "0" + day;
var today = now.getFullYear() + '-' + month + '-' + day;
$('#datePicker').val(today);
});
I would probably put a bit of extra time to see if the month and date are single digits and prefix them with the extra zero...but this should give you an idea.
EDIT: Added check for the extra zero.
Follow the standard Y-m-d format, if you are using PHP
<input type="date" value="<?php echo date("Y-m-d"); ?>">
HTML
<input type="date" id="theDate">
JQuery
$(document).ready(function() {
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "-" + month + "-" + day +"T00:00";
$("#theDate").attr("value", today);
});
demo
If you don't want to use jQuery you can do something like this
JS
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "-" + month + "-" + day;
document.getElementById("theDate").value = today;
demo
TS
const date = new Date()
const year = date.getFullYear()
let month: number | string = date.getMonth() + 1
let day: number | string = date.getDate()
if (month < 10) month = '0' + month
if (day < 10) day = '0' + day
const today = `${year}-${month}-${day}`
document.getElementById("theDate").value = today;
In HTML5 as such, there is no way to set the default value of the date field to today’s date? As shown in other answers, the value can be set using JavaScript, and this is usually the best approach if you wish to set the default according to what is current date to the user when the page is loaded.
HTML5 defines the valueAsDate property for input type=date elements, and using it, you could set the initial value directly from an object created e.g. by new Date(). However, e.g. IE 10 does not know that property. (It also lacks genuine support to input type=date, but that’s a different issue.)
So in practice you need to set the value property, and it must be in ISO 8601 conformant notation. Nowadays this can be done rather easily, since we can expect currenty used browsers to support the toISOString method:
<input type=date id=e>
<script>
document.getElementById('e').value = new Date().toISOString().substring(0, 10);
</script>
If you're doing anything related to date and time in the brower, you want to use Moment.js:
moment().format('YYYY-MM-DD');
moment() returns an object representing the current date and time. You then call its .format() method to get a string representation according to the specified format. In this case, YYYY-MM-DD.
Full example:
<input id="today" type="date">
<script>
document.getElementById('today').value = moment().format('YYYY-MM-DD');
</script>
HTML:
<input type="date" value="2022-01-31">
PHP:
<input type="date" value="<?= date('Y-m-d') ?>">
Date format must be "yyyy-mm-dd"
Javascript
document.getElementById('date-field').value = new Date().toISOString().slice(0, 10);
Jquery
$('#date-field').val(new Date().toISOString().slice(0, 10));
Another Option
If you want to customize the date, month and year just do sum or sub as your wish 😎
For month is started form 0 that is why need to sum 1 with the month.
function today() {
let d = new Date();
let currDate = d.getDate();
let currMonth = d.getMonth()+1;
let currYear = d.getFullYear();
return currYear + "-" + ((currMonth<10) ? '0'+currMonth : currMonth )+ "-" + ((currDate<10) ? '0'+currDate : currDate );
}
Appy the today function
document.getElementById('date-field').value = today();
$('#date-field').val(today());
use moment.js to solve this issue in 2 lines,
html5 date input type only accept "YYYY-MM-DD" this format. I solve my problem this way.
var today = moment().format('YYYY-MM-DD');
$('#datePicker').val(today);
this is simplest way to solve this issue.
Simplest working version I tested:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" id="date" name="date">
<script>
$('#date').val(new Date().toJSON().slice(0,10));
</script>
This is very much simple by applying following code, Using PHP
<input type="date" value="<?= date('Y-m-d', time()); ?>" />
Date function will return current date, by taking date in time().
<input id="datePicker" type="date" />
$(document).ready( function() {
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
$('#datePicker').val(today);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="datePicker" type="date" />
Very Simple, Just use server side languages like PHP,ASP,JAVA or even you can use javascript.
Here is the solution
<?php
$timezone = "Asia/Colombo";
date_default_timezone_set($timezone);
$today = date("Y-m-d");
?>
<html>
<body>
<input type="date" value="<?php echo $today; ?>">
</body>
</html>
Both top answers are incorrect.
A short one-liner that uses pure JavaScript, accounts for the local timezone and requires no extra functions to be defined:
const element = document.getElementById('date-input');
element.valueAsNumber = Date.now()-(new Date()).getTimezoneOffset()*60000;
<input id='date-input' type='date'>
This gets the current datetime in milliseconds (since epoch) and applies the timezone offset in milliseconds (minutes * 60k minutes per millisecond).
You can set the date using element.valueAsDate but then you have an extra call to the Date() constructor.
if you need to fill input datetime you can use this:
<input type="datetime-local" name="datetime"
value="<?php echo date('Y-m-d').'T'.date('H:i'); ?>" />
For NodeJS (Express with SWIG templates):
<input type="date" id="aDate" name="aDate" class="form-control" value="{{ Date.now() | date("Y-m-d") }}" />
The simplest solutions seem to overlook that UTC time will be used, including highly up-voted ones. Below is a streamlined, ES6, non-jQuery version of a couple of existing answers:
const today = (function() {
const now = new Date();
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const day = now.getDate().toString().padStart(2, '0');
return `${now.getFullYear()}-${month}-${day}`;
})();
console.log(today); // as of posting this answer: 2019-01-24
This is what I did in my code, I have just tested and it worked fine, input type="date" does not support to set curdate automatically, so the way I used to overcome this limitation was using PHP code a simple code like this.
<html>
<head></head>
<body>
<form ...>
<?php
echo "<label for='submission_date'>Data de submissão</label>";
echo "<input type='date' name='submission_date' min='2012-01-01' value='" . date('Y-m-d') . "' required/>";
?>
</form>
</body>
</html>
Hope it helps!
It is possible in one line of JS.
HTML:
<input type="date" id="theDate">
JS:
document.getElementById('theDate').value = new Date().toISOString().substring(0, 10);
document.getElementById('theDate').value = new Date().toISOString().substring(0, 10);
<input type="date" id="theDate">
This is something you really need to do server-side as each user's local time format differs, not to mention each browser behaves different.
Html Date inputs value should be in this format: yyyy-mm-dd otherwise it will not show a value.
ASP CLASSIC , OR VBSCRIPT:
current_year = DatePart("yyyy",date)
current_month = DatePart("m",date)
current_day = DatePart("d",date)
IF current_month < 10 THEN
current_month = "0"&current_month
END IF
IF current_day < 10 THEN
current_day = "0"&current_day
END IF
get_date = current_year&"-"&current_month&"-"&current_day
Response.Write get_date
Output of today's date : 2019-02-08
Then in your html:
<input type="date" value="<% =get_date %>"
PHP
just use this:
<input type="date" value="<?= date("Y-m-d"); ?>">
Even after all these time, it might help someone. This is simple JS solution.
JS
let date = new Date();
let today = date.toISOString().substr(0, 10);
//console.log("Today: ", today);//test
document.getElementById("form-container").innerHTML =
'<input type="date" name="myDate" value="' + today + '" >';//inject field
HTML
<form id="form-container"></form>
Similar solution works in Angular without any additional library to convert date format. For Angular (code is shortened due to common component code):
//so in myComponent.ts
//Import.... #Component...etc...
date: Date = new Date();
today: String; //<- note String
//more const ...
export class MyComponent implements OnInit {
//constructor, etc....
ngOnInit() {
this.today = this.date.toISOString().substr(0, 10);
}
}
//so in component.html
<input type="date" [(ngModel)]="today" />
A future proof solution, also an alternative to .split("T")[0] that doesn't create a string array in memory, would be using String.slice() as shown below:
new Date().toISOString().slice(0, -14);
A lot of the answers given here, such as slice(0, 10), substring(0, 10) etc will fail in the future.
They use Date.toJSON() which returns Date.toISOString():
The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix "Z".
Once the year becomes 5 digit, these answers will fail.
datePickerId.value = new Date().toISOString().slice(0, -14);
<input type="date" id="datePickerId" />
To match the original query.
date.value = new Date().toJSON().split('T')[0]
<input type="date" id="date"/>
by Javascript:
var today = new Date();
document.getElementById("theDate").value = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2);
new Date().getFullYear()+"-"+ ((parseInt(new Date().getMonth())+1+100)+"").substring(1)
A simple solution:
<input class="set-today" type="date">
<script type="text/javascript">
window.onload= function() {
document.querySelector('.set-today').value=(new Date()).toISOString().substr(0,10));
}
</script>
This returns in the same YYYY-MM-DD format as in ISO but in your local time instead of being UTC.
function getToday() {
return new Date().toLocaleDateString('en-CA', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
}

splite string using mutilple characters

what I need is simple thing, I have string which cantains data - time retrived from mySQL in mySQL format HH:MM:SS YY-MM-DD what I need is to split this string in actionscript to array of numbers like this
HH
MM
SS
YY
MM
DD
so I can compare it with current time, any one know how to splite using multiple delimiters at first, then compare it with current time. this is my work until now
var param:Array = datetime.split(" :-");
var currentTime:Date = new Date();
var seconds:uint = currentTime.getSeconds();
var minutes:uint = currentTime.getMinutes();
var hours:uint = currentTime.getHours();
var days:uint = currentTime.getDay();
var monthes:uint = currentTime.getMonth();
var years:uint = currentTime.getFullYear();
if(int(param[3]) > years)
return years + " سنة ";
if(int(param[4]) > monthes)
return monthes + " شهر ";
if(int(param[5]) > days)
return days + " يوم ";
if(int(param[0]) > hours)
return hours + " ساعة ";
if(int(param[1]) > minutes)
return minutes + " دقيقة ";
if(int(param[2]) > seconds)
return seconds + " ثانية ";
return param[0] + " يوم ";
`
Split allows the delimiter to be a regexp, so you can say this or that. Something like this:
myStr.split(/:|-/)
Good luck!
You can use multiple characters, with separated by pipe |
myStr.split(/:|-|[|\(|\)]/)
make sure to use \ if you use ( ) and similar, so ( )
To solve your specific question, you might consider replacing the characters to be the same, and then split on that one. Use datetime.replace(/[ :-]/g, "|") and then split on "|". (I didn't check the correctness of the regexp). What Tyler says is more elegant: datetime.split(/[ -:]/). I stand for the rest though:
What MySQL outputs (via php?) is a standard date notation. You could try and use the Date.parse(dateString) to get a timestamp from it, and convert that into a date object by passing it as the sole constructor parameter:
recordedTime = new Date(Date.parse(datetime));
You could then compare the two date objects directly.
if (recordedTime.getFullYear() > currentTime.getFullYear()) { ... }
Hope it helps.