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?
Related
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.
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
This question already has answers here:
moment js is returning wrong formatted values for an iso timestamp
(2 answers)
Closed 3 years ago.
date = moment(startDate).startOf('day');
date.format('2019-01-01't)
Above code is converting UTC date to local date. How do i keep UTC date UTC?
startDate is a datetime string in iso format
From the moment docs:
By default, moment parses and displays in local time.
If you want to parse or display a moment in UTC, you can use
moment.utc() instead of moment().
So even though your datestring is UTC and moment is correctly parsing the date, it still displays the output in local time unless you use moment.utc(). To display in utc:
const s = '2019-03-08T14:59:40Z';
const date = moment.utc(s).startOf('day').format();
console.log(date);
// 2019-03-08T00:00:00Z
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
This question already has answers here:
JavaScript's getDate returns wrong date
(12 answers)
Closed 6 years ago.
This is so basic, but it makes no sense to me:
new Date("2010-01-01").getFullYear();
result: 2009
wth? My goal is to reformat the date as mm/dd/yyyy given the format yyyy-mm-dd..
Adding on:
new Date("2010-01-01").getMonth();
result: 11
new Date("2010-01-01").getDate();
result: 31
The date string you're passing into new Date() has no timezone in it. It's being interpreted as UTC. The critical thing to understand here is that a Date is stored as a Unix timestamp (seconds since 1970-01-01 00:00, making 'Date' a misleading name) so if you don't specify the time within the date, it's going to apply a default.
Date.prototype.getFullYear() retrieves the full year for that timestamp in your LOCAL time. (See the docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear)
You're somewhere west of UTC, and 2010-01-01 UTC is 2009-12-31 in your local time.
And for your final mystery....getMonth() is 0-based, not 1-based, so '11' is December.
Don't use the Date constructor to parse strings, it's largely implementation dependent and inconsistent.
An ISO 8601 date and time without a timezone like "2016-02-29T12:00:00" should be treated as local (i.e. use the host system timezone offset to create a Date), but a date–only string is treated like "2016-02-29" as UTC. The first behaviour is consistent with ISO 8601, but the second isn't.
Some versions of browsers will treat date–only strings as UTC, and some as invalid dates, so always parse strings manually (a two line function or library can help). That way you know how it will be parsed in all hosts.
Provide Time with date in the new Date() as parameter . Then u will get exact Result.
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());