Deprecation warning: moment construction falls back to js Date - javascript

I am attempting to convert this datetime
150423160509 //this is utc datetime
To the following format:
2015-04-24 00:05:09 //local timezone
by using the moment.js
var moment = require('moment-timezone');
var a = moment.tz('150423160509', "Asia/Taipei");
console.log( a.format("YYYY-MM-DD H:m:s") );
but it gives me this error
Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release

You need to tell moment how to parse your date format, like this:
var parsedDate = moment.utc("150423160509", "YYMMDDHHmmss");
var a = parsedDate.tz("Asia/Taipei");
// I'm assuming you meant HH:mm:ss here
console.log( a.format("YYYY-MM-DD HH:mm:ss") );

This is what i found when I typed "moment construction falls back to js Date" in Google. (From a post of Joe Wilson)
To get rid of the warning, you need to either:
Pass in an ISO formatted version of your date string:
moment('2014-04-23T09:54:51');
Pass in the string you have now, but tell Moment what format the string is in:
moment('Wed, 23 Apr 2014 09:54:51 +0000', 'ddd, DD MMM YYYY
HH:mm:ss ZZ');
Convert your string to a JavaScript Date object and then pass that into Moment:
moment(new Date('Wed, 23 Apr 2014 09:54:51 +0000'));
The last option is a built-in fallback that Moment supports for now,
with the deprecated console warning. They say they won't support this
fallback in future releases. They explain that using new Date('my
date') is too unpredictable.
Hope that helped ;)

Related

Moment.js doesn't recognize ISO date format

While adding a new item to my database I'm creating a new date to it by:
const item = new Item({
author,
isOrdered,
name,
createdAt: new Date(Date.now()).toISOString()
});
When sorting items, the moment.js is called and it warns me in the console
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 and will be removed in an upcoming major
release. Please refer to
http://momentjs.com/guides/#/warnings/js-date/ for more info.
The date format that I'm saving to db is 2019-01-09T07:55:34.665Z.
I've been reading the documentation and by following the instructions I did something like this, to specify the date format:
moment('2019-01-09T07:55:34.665Z', 'ddd, D MMM YYYY H:m:s Z')
but still, it throws me a warning. How to workaround this warning?
try to specify the format separately like,
moment('2019-01-09T07:55:34.665Z').format('ddd, D MMM YYYY H:m:s Z')
'Wed, 9 Jan 2019 15:55:34 +08:00'
I would prefer to see the database applying the timestamp. This would depend a bit on what db and potentially orm you're using.
In javascript, as mentionned in the comments, just do...
createdAt : new Date().toISOString()

Date format being sent by REST API is Invalid in IE 11

I am currently making a series of REST calls to a backend API and I have no control over the format of the date being sent back in the JSON.
The format that is being sent is this
Wed, 21 Nov 2018 03:00:00.000Z
IE11 considers this an invalid date. I have been using moment.js to get the current date and time and comparing it to the date and time being sent in the API. It is working perfectly everywhere except in IE. I have been trying everything I can from the Moment docs but everything that I return is considered invalid by IE11.
I am setting my date as follows
var date = new Date("Wed, 21 Nov 2018 03:00:00.000Z");
Update: I have also tried setting the date using moment
var date = "Wed, 21 Nov 2018 03:00:00.000Z"
date = moment(d, "YYYY-MM-DD HH:mm:ss").toDate();
I have tried many different formats and everything returns invalid.
This is what returns as Invalid according to IE. I have tried converting the date to a moment object first and then into a valid date format but that has not seemed to work either.
I was able to conclude that IE does not like the .000Z at the end of the date. It works if I cut that off but that all my times are in GMT.
The format YYYY-MM-DD HH:mm:ss you're putting in your momentJS constructor bears no resemblance to the date string you're actually inputting...you're telling moment to expect something like "2018-11-16 17:10:02". Maybe you've confused this with the format you want to output later, I'm not sure, because it clearly doesn't even come close to matching the example data.
Check http://momentjs.com/docs/#/parsing/string-format/ and choose the appropriate tokens to match the date format you're providing. Here's an example which will work for the date given in the example:
var d = "Wed, 21 Nov 2018 03:00:00.000Z";
var m = moment(d, "ddd, DD MMM YYYY HH:mm:ss.SZ"); //parse the date based on the format tokens given
console.log(m.format("YYYY-MM-DD HH:mm:ss")); //output the date in a different format
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Properly formatting a local UTC date string when dealing with an Arabic locale

I'm using moment.js and moment-timezone to get a local utc date string. I've created the function below to achieve this. When trying to use this when dealing with an Arabic locale I'm getting invalid date returned.
function _getLocalUtcDateString(utcDateString, timezoneId) {
var utcMoment = moment.utc(utcDateString, 'MM/DD/YYYY hh:mm:ss A').format('MM/DD/YYYY hh:mm:ss A');
var localTimeTz = moment.utc(utcMoment).tz(timezoneId).format('MM/DD/YYYY hh:mm:ss A');
return localTimeTz;
}
If I call it with the following parameters _getLocalUtcDateString("11/2/2016 4:45:47 PM", "America/New_York") and set moment.locale('ar') it fails with invalid date. The problem seems to be with utcMoment, when the lacale is Arabic this value equals ١١/٠٢/٢٠١٦ ٠٤:٤٥:٤٧ ص which is causing moment.utc(utcMoment).tz(timezoneId).format('MM/DD/YYYY hh:mm:ss A'); to fail.
If you open the console, you will see the following warning message:
Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
So the problem is the you are trying to parse a string that isn't in a recognized ISO format (see parsing docs for additional infos).
To fix the issue, you can simply remove the unnecessary format() in the first line of your function, as shown in the following working snippet:
function _getLocalUtcDateString(utcDateString, timezoneId) {
var utcMoment = moment.utc(utcDateString, 'MM/DD/YYYY hh:mm:ss A');
var localTimeTz = moment.utc(utcMoment).tz(timezoneId).format('MM/DD/YYYY hh:mm:ss A');
return localTimeTz;
}
moment.locale('ar');
var res = _getLocalUtcDateString("11/2/2016 4:45:47 PM", "America/New_York");
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.7/moment-timezone-with-data-2010-2020.min.js"></script>

How to parse date string from database without time shift?

I am getting 2016-07-13T00:00:00.000Z string from database and converting it to MM/DD/YYYY format with moment.js like this:
result = moment('2016-07-13T00:00:00.000Z').format('MM/DD/YYYY');
which prints 07/12/2016 but I was expecting 07/13/2016.
Local Linux timezone is America/New_York. date command prints this Mon Jul 4 04:28:19 EDT 2016
The date that you have is in UTC, as signified by the z at the end.
When you use the default moment constructor, moment(), it converts the time you pass it from the specified offset (in this case UTC) to the local time of the machine. This is why your date is changing. Because this is a UTC date, to keep it exactly the same you can use moment.utc():
moment.utc('2016-07-13T00:00:00.000Z').format('MM/DD/YYYY');
"07/13/2016"
Alternately, parseZone would work as well:
moment.parseZone('2016-07-13T00:00:00.000Z').format('MM/DD/YYYY');
"07/13/2016"
For more information about all of the constructor functions in moment, see the parsing guide
or this blog post
You should use momentjs timezone : http://momentjs.com/timezone/
yourdate = moment.tz("2016-07-13T00:00:00.000Z", "America/New_York");
alert(yourdate.format('MM/DD/YYYY'));
This should give you the correct date in output.

Format date with Moment.js

I have a string in this format:
var testDate = "Fri Apr 12 2013 19:08:55 GMT-0500 (CDT)"
I would like to use Moment.js get it in this format mm/dd/yyyy : 04/12/2013 for display.
I tried to do it using this method,
moment(testDate,'mm/dd/yyyy');
Which errors and says there is no such method called replace? Am I approaching this in the wrong way?
Edit
I should also mention that I am using a pre-packaged version of Moment.js, packaged for Meteor.js
Object [object Date] has no method 'replace' : The Exact error from the console
Stack Trace:
at makeDateFromStringAndFormat (http://127.0.0.1:3000/packages/moment/lib/moment/moment.js?b4e3ac4a3d0794023a4410e7941c3e179398b5b0:539:29)
at moment (http://127.0.0.1:3000/packages/moment/lib/moment/moment.js?b4e3ac4a3d0794023a4410e7941c3e179398b5b0:652:24)
at populateProfileForEdit (http://127.0.0.1:3000/client/views/home/administration/directory/profiles/profiles.js?acfff908a6a099f37312f62892a22b40f82e5e0f:147:25)
at Object.Template.profile_personal.rendered (http://127.0.0.1:3000/client/views/home/administration/directory/profiles/profiles.js?acfff908a6a099f37312f62892a22b40f82e5e0f:130:13)
at Spark.createLandmark.rendered (http://127.0.0.1:3000/packages/templating/deftemplate.js?b622653d121262e50a80be772bf5b1e55ab33881:126:42)
at http://127.0.0.1:3000/packages/spark/spark.js?45c746f38023ceb80745f4b4280457e15f058bbc:384:32
at Array.forEach (native)
at Function._.each._.forEach (http://127.0.0.1:3000/packages/underscore/underscore.js?867d3653d53e9c7a171483edbcad9670e12288c7:79:11)
at http://127.0.0.1:3000/packages/spark/spark.js?45c746f38023ceb80745f4b4280457e15f058bbc:382:7
at _.extend.flush (http://127.0.0.1:3000/packages/deps/deps.js?9642a93ae1f8ffa8eb1c2475b198c764f183d693:231:11)
The 2nd argument to moment() is a parsing format rather than an display format.
For that, you want the .format() method:
moment(testDate).format('MM/DD/YYYY');
Also note that case does matter. For Month, Day of Month, and Year, the format should be uppercase.
Include moment.js and using the below code you can format your date
var formatDate= 1399919400000;
var responseDate = moment(formatDate).format('DD/MM/YYYY');
My output is "13/05/2014"
moment().format(); // "2019-08-12T17:52:17-05:00" (ISO 8601, no fractional seconds)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, August 12th 2019, 5:52:00 pm"
moment().format("ddd, hA"); // "Mon, 5PM"
You Probably Don't Need Moment.js Anymore
Moment is great time manipulation library but it's considered as a legacy project, and the team is recommending to use other libraries.
date-fns is one of the best lightweight libraries, it's modular, so you can pick the functions you need and reduce bundle size (issue & statement).
Another common argument against using Moment in modern applications is its size. Moment doesn't work well with modern "tree shaking" algorithms, so it tends to increase the size of web application bundles.
import { format } from 'date-fns' // 21K (gzipped: 5.8K)
import moment from 'moment' // 292.3K (gzipped: 71.6K)
Format date with date-fns:
// moment.js
moment().format('MM/DD/YYYY');
// => "12/18/2020"
// date-fns
import { format } from 'date-fns'
format(new Date(), 'MM/dd/yyyy');
// => "12/18/2020"
More on cheat sheet with the list of functions which you can use to replace moment.js: You-Dont-Need-Momentjs
var moment = require('moment');
let yourdate = '2021-01-02T07:57:45.121Z'; // for example
moment(yourdate).format('MM/DD/YYYY');
// output : 01-02-2021
moment(yourdate).format('DD-MMM-YYYY');
// output : 01-Jan-2021
For fromating output date use format. Second moment argument is for parsing - however if you omit it then you testDate will cause deprecation warning
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format...
var testDate= "Fri Apr 12 2013 19:08:55 GMT-0500 (CDT)"
let s= moment(testDate).format('MM/DD/YYYY');
msg.innerText= s;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<div id="msg"></div>
to omit this warning you should provide parsing format
var testDate= "Fri Apr 12 2013 19:08:55 GMT-0500 (CDT)"
let s= moment(testDate, 'ddd MMM D YYYY HH:mm:ss ZZ').format('MM/DD/YYYY');
console.log(s);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
You can pass "L" to format method, which handles internationalisation...
moment.locale('en-US');
moment().format("L");
> "06/23/2021"
moment.locale('fr');
moment().format("L");
> "23/06/2021"
Other long date formats (fr locale):
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY HH:mm',
LLLL : 'dddd D MMMM YYYY HH:mm'
Docs: https://momentjs.com/docs/#/displaying/format/ (see "Localized formats")
To get the current UTC time in YYYY-MM-DD HH:MM:ss.Millisecond with timezone using moment format as below
moment().utc().format('Y-MM-DD HH:mm:ss.SSS Z').
Output
2022-09-20 15:28:39.446 +0000
May be this helps some one who are looking for multiple date formats one after the other by willingly or unexpectedly.
Please find the code:
I am using moment.js format function on a current date as (today is 29-06-2020)
var startDate = moment(new Date()).format('MM/DD/YY'); Result: 06/28/20
what happening is it retains only the year part :20 as "06/28/20", after If I run the statement :
new Date(startDate)
The result is "Mon Jun 28 1920 00:00:00 GMT+0530 (India Standard Time)",
Then, when I use another format on "06/28/20": startDate = moment(startDate ).format('MM-DD-YYYY'); Result: 06-28-1920, in google chrome and firefox browsers it gives correct date on second attempt as: 06-28-2020. But in IE it is having issues, from this I understood we can apply one dateformat on the given date, If we want second date format, it should be apply on the fresh date not on the first date format result.
And also observe that for first time applying 'MM-DD-YYYY' and next 'MM-DD-YY' is working in IE.
For clear understanding please find my question in the link:
Date went wrong when using Momentjs date format in IE 11

Categories

Resources