This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
I am trying to extract date from a string 20170901000000. new Date(string) returns Invalid Date. The date string looks pretty straightforward to me but apparently javascript doesn't take it.
What formats does javascript new Date() method take? Is there a package taking more formats of date string?
Edit: The formats are from random users. The YYYYMMDDhhmmss is only one example. The package has to be able to determine what format it is by itself and parse it.
You have to parse your date string:
parseDateString = dateStr =>
dateStr.replace(
/^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})$/,
'$1-$2-$3 $4:$5:$6'
);
console.log(new Date(parseDateString('20170901000000')));
Hope this helps,
you can split that string and use this..
new Date (YYYY,MM,DD,HH,MM,SS)
/* from mdn */
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
Use a propper library like Moment.js:
const date = moment("20170901000000", "YYYYMMDDhhmmss");
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
When using a number passed to the date function it must be in the format of a unix timestamp.
new Date(value): A Unix Time Stamp which is an integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored (Unix Epoch; but consider that most Unix timestamp functions count in seconds).
Otherwise you need to generate a valid time string:
new Date(dateString): String value representing a date. The string should be in a format recognized by the Date.parse() method
Since your format is YYYYMMDDHHMMSS and not a unix timestamp we can use the latter dateString approach and use regex to create a valid string date:
let format = '20170901000000'
.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1-$2-$3 $4:$5:$6')
console.log('format:', format)
console.log('date:', new Date(format))
Also see the [document for Javascript Date.parse][1]
Examples
new Date('2017-09-01 00:00:00');
new Date('Sept 01, 2017 00:00:00');
For more libraries you can use Moment.js or Day.js
Related
This question already has answers here:
Deprecation warning in Moment.js - Not in a recognized ISO format
(18 answers)
Closed 1 year ago.
I need to find difference between 2 dates in seconds , i am passing one date from front end and another date is current date but i am getting error
here is my code in front end
var a =moment().format('MM/DD/YYYY HH:mm:ss')
here is nodeJs code that I need to compare
var sesdate=moment(request.body.a).format("DD/MM/YYYY HH:mm:ss")
var startDate = moment(sesdate, "DD/MM/YYYY HH:mm:ss");
var currenDate = moment(new Date()).format("DD/MM/YYYY HH:mm:ss");
var endDate = moment(currenDate, "DD/MM/YYYY HH:mm:ss");
var result = 'Diff: ' + endDate.diff(startDate, 'seconds');
but i am getting expected output but getting warning message as
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
If you already have two JavaScript DateTime objects, you can use the .getTime() method to get the milliseconds since 1970. Subtract one from the other and divide by 1000 to convert to seconds. You may need to take the absolute value if it's not guaranteed that one of them is always after the other.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime
Alternatively, if you want to stick to your moment code, you'll need to convert your time format to one that is RFC2822 / ISO compatible. The top answer to this question will show you how to do that:
How do I format a date as ISO 8601 in moment.js?
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
Trying to get UTC day of the week for any given timestamp on any given machine (w/ their own local time) I used:
var date = new Date(timestamp).toLocaleString('en-GB', { timeZone: 'UTC' });
Once I try to convert the date string to UTC date I get Invalid Date for some dates... it all seems pretty weird.
$ node
> date = new Date('15/08/2019, 00:00:00');
Invalid Date
> date = new Date('12/08/2019, 00:00:00');
2019-12-08T00:00:00.000Z
> date = new Date('15/08/2019');
Any idea where the Invalid Date issue may come from?
By converting the timestamps to strings using the "en-GB" locale, it looks like you're getting them in DD/MM/YYYY format. But in your second example, the strings are being interpreted as "MM/DD/YYYY" in whatever your default locale is, so the first call fails because 15 isn't a valid month number.
I need to convert date to Java epoch and then read it and convert back. Not sure what I'm doing wrong here?
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(timeStamp);
var revertDate = new Date(timeStamp);
console.log(revertDate.getDate()+'/'+revertDate.getMonth()+'/'+revertDate.getFullYear());
The output is 3/0/2013 instad 1/3/2013?
fiddle link
You've got two problems here:
The Date constructor is assuming M/d/yyyy format - whereas you're logging d/M/yyyy format. Personally I'd suggest using an ISO-8601 format if at all possible: yyyy-MM-dd
You're not taking into account the fact that getMonth() returns a 0-based value
For the formatting side, you'd be better off using toISOString or something similar, rather than doing the formatting yourself.
(Note that looking at the documentation for the Date constructor it's not clear that the code you've got should work at all, as it's neither an RFC822 nor ISO-8601 format.)
Neither of the problems are to do with converting between Date and a numeric value. If you change your logging, you'll see that clearly:
var date = new Date('1/3/2013');
var timeStamp = date.getTime();
console.log(date);
var revertDate = new Date(timeStamp);
console.log(revertDate);
var date = new Date('1/3/2013');
The Date constructor is parsing this given string this way:
Month / Day / Year
So, in this case, Month is 1, Day is 3 and Year is 2013. What's going on there? Well that's quite simple. This Gregorian representation of a date(which is specifically Day / Month / Year ) isn't the one used by the Date constructor, so it will parse the 1(the month) as January, the 3 as the third day of the month(the third of Jan) and the year correctly, the 2013. Now, due to its 0-based indexing, the constructed Date object will return a month which is n-1 among the one provided. That's why you're getting 3/0/2013. It is the third day(3) of the month 0(which is January) of 2013. If you want to get your real date you have to do this:
var date = new Date('3/1/2013');
console.log(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear());
How can I convert a date from:
Thu, 1 July 2011 22:30:00 to '2011-07-01T13:51:50.417' using javascript.
I get the UTC format when I do a new date.
IE causes me issues when I first create a date object as it shows: NaN
You could generate a new Date-Object and then get the different parts:
var today = new Date();
var year = today.getFullYear(); // Returns 2012
var month = today.getMonth()+1; // Returns the month (zero-based)
...
Then you can create a new string like you need it.
possible duplicate try search next time
stackoverflow question
Try http://www.datejs.com/. It is a JavaScript Date Library with an extended Date.parse method and a Date.parseExact method, which lets you specify a format string. See DateJS APIDocumentation.
and then you can manipulate it as you want
The d3.js library has some very solid routines for date conversions. See https://github.com/mbostock/d3/wiki/Time-Formatting#wiki-parse.
I am facing a weird problem while initializes javascript date object,no matter what I initialize to it shows the date as 1 JAN 1970 05:30;
this is the way I try to initialize
var d=new date(27-02-1989);
alerting 'd' shows 1 JAN 1970.....,also sometimes it takes a date passed from the database but in the format as mm/dd/yyyy not in the format I want i.e dd/mm/yyyy
This problem has suddenly popped-up, as everything was working smooth couple of days ago,but today after opening the project (after 2 days) this issue is irritating me
I see you've accepted an answer, but it isn't the best you can do. There is no one format that is parsed correctly by all browsers in common use, the accepted answer will fail in IE 8 at least.
The only safe way to convert a string to a date is to parse it, e.g.
var s = '27-02-1989';
var bits = s.split('-');
var date = new Date(bits[2], --bits[1], bits[0]);
// Transform your european date in RFC compliant date (american)
var date = '27-02-1989'.split('-').reverse().join('-');
// And this works
var d = new Date( date );
Proof:
You're doing an initialization with a negative integer value (27-02-1989 == -1964). The Date object's constructor takes arguments listed here.
If you want to pass strings, they need to be in an RFC2822-compliant format (see here).
according to here you can try:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond ])
so for your case use (edit: You need to remember that months are zero based)
var d = new Date(1989,01,27);
pleas notice - use Date (capital D)
First of all
var d=new date(27-02-1989);
is totaly wrong expression in javascript, moreover even if we rewrites it more correctly:
var d=new Date('27-02-1989');
there is no way to parse this date string natively in js.
Here solutions you can try:
transform string to ISO8601: YYYY-mm-dd, this can be parsed by most modern broswers, or you can use many js libraries for polyfill
split string string by '-' and then use Date constructor function new Date(year, month-1, day)
split string and use setDate, setMonth, setYear method on new Date() object
Note that in last two methods you need to deduct 1 from month value, because month is zero-based (0 stands for January, 11 for December)