Moment.js with a format zulu and format date javascript - javascript

I have this format date:
01Mar-0234
26Feb-0430
01 is day, mar or feb is mounth and 0430 is 4 oclock 30 in formater zulu +00.
I would like to use moment for converting this format, I'm trying this:
moment('26Feb-0430').format("DD-MM-YY HH:MM");
but I haven't good format and I have this error :
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment c
onstruction falls back to js Date(), which is not reliable across all browsers and version
s. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major r
elease. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments:
Can you help me for have 26/02/2017 06:30 for summer and 5h30 winter?

As suggested in the comments and in the warning message you have to use moment(String, String) parsing function.
In the format string parameter you have to use moment tokens where: DD is day of the month. MMM is month's short name, HH is 0-23 hours and mm (lowercase) is minutes.
Since you have to threat your input as +00:00, you have to use moment.utc.
Use format() to display the parsed moment object passing the tokens you need, always remember that moment tokens are case sensitive.
Here a working sample:
var result = moment.utc('26Feb-0430', 'DDMMM-HH:mm').format("DD/MM/YYYY HH:mm");
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Related

MomentJS: how to parse dates in MM/DD/YYYY & DD/MM/YYYY

How can i use moment.js in both: Australia & USA time formats?
For example:
07/08/2017 - is good for both time formats, but!
30/08/2017 - is invalid for moment.js, but i can have such dateTime
You can check it here:
http://jsfiddle.net/rLjQx/2135/
The parser is assuming that digits of the form XX-XX-XXXX are representing DD-MM-YYYY. If you'd like it to accept MM-DD-YYYY then you need to specify this.
eg var now2 = moment('08/30/2017', 'MM-DD-YYYY').format('MMM DD h:mm A');
You can also specify an array of different formats that you'd like it to accept so that it will recognise both:
var now2 = moment('08/30/2017', ['DD-MM-YYYY', 'MM-DD-YYYY']).format('MMM DD h:mm A');
Specify the format via a second parameter to the moment call
var now2 = moment('30/08/2017', 'DD/MM/YYYY').format('MMM DD h:mm A');
Otherwise there is no way for moment to know
Related docs here: https://momentjs.com/docs/#/parsing/string-format/
Corrected fiddle: http://jsfiddle.net/wu6wwsvp/
In your fiddle you are using a very old version of moment (2.2.1), I suggest to upgrade it to lastest one (2.18.1).
Using a newer version, you will have a Deprecation Warning in your 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.
Following the link (and moment(String) docs) you will discover that you have to specify format to parse you string correctly.
As Billy Reilly suggested you can use moment(String, String[]) parsing function. Please remeber that:
Starting in version 2.3.0, Moment uses some simple heuristics to determine which format to use. In order:
Prefer formats resulting in valid dates over invalid ones.
Prefer formats that parse more of the string than less and use more of the format than less, i.e. prefer stricter parsing.
Prefer formats earlier in the array than later.
So the way 07/08/2017 will be interpreted depends on the order of the format in array of formats parameter.
Here a snippet with some examples:
var now = moment('30/08/2017', ['MM/DD/YYYY','DD/MM/YYYY']);
var now2 = moment('08/30/2017', ['MM/DD/YYYY','DD/MM/YYYY']);
var now3 = moment('07/08/2017', ['MM/DD/YYYY','DD/MM/YYYY']);
console.log(now.format('MMM DD h:mm A')); // Aug 30 12:00 AM
console.log(now2.format('MMM DD h:mm A'));// Aug 30 12:00 AM
console.log(now3.format('MMM DD h:mm A'));// Jul 08 12:00 AM
var now4 = moment('30/08/2017', ['DD/MM/YYYY','MM/DD/YYYY']);
var now5 = moment('08/30/2017', ['DD/MM/YYYY','MM/DD/YYYY']);
var now6 = moment('07/08/2017', ['DD/MM/YYYY','MM/DD/YYYY']);
console.log(now4.format('MMM DD h:mm A')); // Aug 30 12:00 AM
console.log(now5.format('MMM DD h:mm A')); // Aug 30 12:00 AM
console.log(now6.format('MMM DD h:mm A')); // Aug 07 12:00 AM
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Deprecation warning: moment construction falls back to js Date (in html or ts) [duplicate]

I am using the following code to convert a server-side date-time to local time using moment.js.
moment(moment('Wed, 23 Apr 2014 09:54:51 +0000').format('lll')).fromNow()
But I am getting:
Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.
It seems I cannot get rid of it! How can I fix it?
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.
As an alternative, you can suppress showing the deprecation warning by setting moment.suppressDeprecationWarnings = true;
The date construction in moment internally uses the new Date() in the javascript. The new Date() construction recognizes the date string in either RFC2822 or ISO formats in all browsers. When constructing a moment object with date not in these formats, the deprecation warning is thrown.
Though the deprecation warnings are thrown, for some formats, the moment object will be successfully constructed in Chrome, but not in Firefox or Safari. Due to this, processing the date in Chrome may give results as expected(not all the time) and throws Invalid Date in others.
Consider, 02.02.2018,
Chrome - moment("02.02.2018")._d -> Fri Feb 02 2018 00:00:00 GMT+0530 (India Standard Time)
Firefox - moment("02.02.2018")._d -> Invalid Date
Safari - moment("02.02.2018")._d -> Invalid Date
So the moment.js is used at your own risk in case the recommended/standard formats are not used.
To suppress the deprecation warnings,
As suggested by #Joe Wilson in previous answer, give the date format on moment construction.
Example : moment("02.05.2018", "DD.MM.YYYY").format("DD MM YYYY");
Give the date in ISO or RFC2822 format.
Example : moment("2018-02-01T18:30:00.000Z") - ISO Format
moment("Thu, 01 Feb 2018 18:30:00 GMT") - RFC2822 Format - Format in Github
As suggested by #niutech in previous answer, set
moment.suppressDeprecationWarnings = true;
I suggest to overwrite the input fallback in moment.
moment.createFromInputFallback=function (config){
config._d = new Date(config._i);
}
As (3) will suppress all the warnings, (4) will suppress only the date construction fallback. Using (4), you will get Invalid Date as the internal new Date() is used and other deprecations can be seen in console, so moment can be upgraded or the deprecated methods can be replaced in the application.
If your date is passed to you from an API as string(like my issue), you can use a filter to convert the string to a date for moment. This will take care of the moment construction warning.
$scope.apiDate = 10/29/2017 18:28:03";
angular.module('myApp').filter('stringToDate', function() {
return function(value) {
return Date.parse(value);
};
});
Add it to the view:
{{apiDate | stringToDate | amDateFormat:'ddd, MMM DD'}}
In my case I was trying to generate a date time to include in my form data. But the format of the string I had access to looked like "10-Sep-2020 10:10" so when trying to use moment like
myDate = '10-Sep-2020 10:10';
moment(myDate).format('YYYY-MM-DD HH:mm:ss');
I got the deprecation warning. There is no problem using a string to create the date but you just have to let moment know what it is you are passing in. As in explicitly state the format it is about to receive, for example
moment(myDate, 'DD-MMM-YYYY HH:mm').format('YYYY-MM-DD HH:mm:ss');
result: 2020-09-10 10:10:00
That's it, the warning goes away, moment is happy and you have a date time format ready for persistence.
As indicated in the above answers. Providing the date format should work.
Why would I be getting the deprecation message with the following line of code. I thought the String + format was suppose to remedy the issue. moment.tz('2015:08:20 14:33:20', 'YYYY:MM:DD HH:mm:ss', 'America/New_York'). Also, please not I do not have control over the date format being provide. I know I can convert it myself to 'YYYY-MM-DDTHH:mm:ss' then moment does not show the deprecation message. However, according to the documentation, the line of code should work. Here is the deprecation message I am seeing.
"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."
Moment’s usage is so widespread that it’s impossible to deprecate the current version over time. Check out this post on alternative options Migrating away from moment.js

Moment.js Sql Date Time Conversion with Nodejs

i am using nodejs to connect to mySql and connection works.
while using query such as
SELECT * from someTable
i get the required results. But the problem is that i am having
a column which stores date is having the given format.
before sending the data i need this format to be converted and vice versa
file_date : Wed Jan 01 2014 05:34:53 GMT+0530 (IST)
This is format i am getting
i am unable to send params with Date in this format from client side
so i need to convert this data to "DD-MM-YYYY" format.i need this way so that i can pass params in "DD-MM-YYYY" and fetch data date wise
Simple Approach
If you know your date format is supported in Moment, then the simplest approach is to construct a moment object and format it.
var file_date = 'Wed Jan 01 2014 05:34:53 GMT+0530 (IST)';
var formatted = moment(file_date).format('DD-MM-YYYY');
Deprecation Warning:
However, at some point support for non ISO date formats was deprecated. It will in some cases still work but you should be warned (per the deprecation 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.
Workaround
Instead, if you know the format of an input string, you can use that to parse a moment.
var s = 'Wed Jan 01 2014 05:34:53 GMT+0530 (IST)';
var m = moment(s, 'ddd MMM DD YYYY hh:mm:ss [GMT]ZZ').format('MM-DD-YYYY');
console.log(m);
<script src="https://momentjs.com/downloads/moment.min.js"></script>
When specifying a format manually like this, it helps to have the format documentation handy: https://momentjs.com/docs/#/displaying/format/

Any way to parse a time string using Moment.js but ignore timezone info?

Given the volume of Timezone questions, I would have thought to be able to find the answer to this issue, but haven't had any success.
Is there a way using moment.js to parse an ISO-8601 string but have it parsed in my local timzeone? Essentially I want to ignore the timezone information that is supplied in the ISO string.
For example, if I am in EDT timezone:
var x = moment( "2012-12-31T00:00:00+0000" );
will give me:
"2012-12-30T19:00:00-5000"
I'm looking to ignore the timezone info and just have it give me a moment equivalent of "2012-12-31T00:00:00-5000" local time (EDT).
I don't think you really want to ignore the offset. That would ultimately just be replacing the offset you provided with one from your local time zone - and that would result in a completely different moment in time.
Perhaps you are just looking for a way to have a moment retain the time zone it was given? If so, then use the moment.parseZone function. For example:
var m = moment.parseZone("2012-12-31T00:00:00+0000");
var s = m.format(); // "2012-12-31T00:00:00+00:00"
You could also achieve this with moment.utc. The difference is that moment.parseZone will retain whatever offset you give it, while moment.utc will adjust to UTC if you give it a non-zero offset.
I solved this by supplying a format as the second argument, and using Moment's method of escaping characters, and wrapped square brackets around the timezone.
moment("2016-01-01T05:00:00-05:00", "YYYY-MM-DDTHH:mm:ss[Z]").startOf("hour").format()
This will still create moment objects using your local time zone, but it won't do any sort of auto-timezone calculation. So the above example will give you 5am regardless of timezone supplied.
I know I'm late to the party, I had the same question and my searches didn't bring me any closer. I broke down and read the documentation and there is an option in moment for a String + Format:
String + Format docs
moment(String, String);
moment(String, String, String);
moment(String, String, Boolean);
moment(String, String, String, Boolean);
and more words, then this:
Unless you specify a time zone offset, parsing a string will create a date in the current time zone.
moment("2010-10-20 4:30", "YYYY-MM-DD HH:mm"); // parsed as 4:30 local time
moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z"); // parsed as 4:30 UTC
The part that gave me pause was the example that was used to parse local time omitted the +0000, which lead me to think the input string needed to have that removed, but it doesn't.
example:
var time = "2012-12-31T00:00:00+0000";
var x = moment(time); // Sun Dec 30 2012 19:00:00 GMT-0500
var y = moment(time,'YYYY-MM-DD'); //Mon Dec 31 2012 00:00:00 GMT-0500
You can ignore the browser's timezone completely by creating a new moment using moment.utc() instead of moment().
For example, if you are trying to work purely with a UTC date/time of the browser's current time but want to discard its timezone data, you can recreate the browser's current time into a UTC format using the following:
let nowWithTimezone = moment();
let nowInUtc = moment.utc(nowWithTimezone.format('MM/DD/YYYY HH:mm'), 'MM/DD/YYYY HH:mm');
Further documentation on moment.utc(): https://momentjs.com/docs/#/parsing/utc/
If you know for sure your input string is in the ISO-8601 format, you could just strip off the last 5 digits and use that in the Moment constructor.
var input = "2012-12-31T00:00:00+0000"
input = input.substring(0, input.length-5)
moment(input).toString()
> "Mon Dec 31 2012 00:00:00 GMT-0600"
There are valid reasons to do what the OP is asking for. The easiest way to do this with Moment is using its parseZone(date) method. No futzing around with string manipulation or multiple calls. It effectively parses the date string as though it were in the browser's local time zone.
This is difficult task to do with MomentJS, it will basically depend as well on your current timezone.
Documentation as well is vague for this specific task, the way I solved the issue on my side was by adding hours to the date before converting it to JSON format.
var dt = moment("Sun Sep 13 2015 00:00:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400", false);
var date = dt.add(2, 'hour').toJSON();
console.log(date); //2015-09-13T00:00:00.000Z
Momentjs default logic will format the given time with local timezone. To format original date, I wrote a function:
https://github.com/moment/moment/issues/2788#issuecomment-321950638
Use moment.parseZone to convert without taking into account the timezone.
const moment = require('moment')
const dateStr = '2020-07-21T10:00:00-09'
const date = moment.parseZone(dateStr)
console.log(date.format('MM-DD-YY HH:mm A')) // 07-21-20 10:00 AM
Try here link to docs
The best way is to use:
dt = moment("Wed Sep 16 2015 18:31:00 GMT-0400", "ddd MMM DD YYYY HH:mm:ss GMT-0400",true);
And to display convert again to desired timezone:
dt.utcOffset("-04:00").toString()
output > Wed Sep 16 2015 18:31:00 GMT-0400

moment.js - UTC gives wrong date

Why does moment.js UTC always show the wrong date. For example from chrome's developer console:
moment(('07-18-2013')).utc().format("YYYY-MM-DD").toString()
// or
moment.utc(new Date('07-18-2013')).format("YYYY-MM-DD").toString()
Both of them will return "2013-07-17" why is it returning 17th instead of 18th, that was passed in.
But if I use momentjs without the utc:
moment(new Date('07-18-2013')).format("YYYY-MM-DD").toString()
I get back "2013-07-18" which is what I also expect when using moment.js UTC.
Does this mean we cannot get the correct date when using moment.js UTC?
By default, MomentJS parses in local time. If only a date string (with no time) is provided, the time defaults to midnight.
In your code, you create a local date and then convert it to the UTC timezone (in fact, it makes the moment instance switch to UTC mode), so when it is formatted, it is shifted (depending on your local time) forward or backwards.
If the local timezone is UTC+N (N being a positive number), and you parse a date-only string, you will get the previous date.
Here are some examples to illustrate it (my local time offset is UTC+3 during DST):
>>> moment('07-18-2013', 'MM-DD-YYYY').utc().format("YYYY-MM-DD HH:mm")
"2013-07-17 21:00"
>>> moment('07-18-2013 12:00', 'MM-DD-YYYY HH:mm').utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 09:00"
>>> Date()
"Thu Jul 25 2013 14:28:45 GMT+0300 (Jerusalem Daylight Time)"
If you want the date-time string interpreted as UTC, you should be explicit about it:
>>> moment(new Date('07-18-2013 UTC')).utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
or, as Matt Johnson mentions in his answer, you can (and probably should) parse it as a UTC date in the first place using moment.utc() and include the format string as a second argument to prevent ambiguity.
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"
To go the other way around and convert a UTC date to a local date, you can use the local() method, as follows:
>>> moment.utc('07-18-2013', 'MM-DD-YYYY').local().format("YYYY-MM-DD HH:mm")
"2013-07-18 03:00"
Both Date and moment will parse the input string in the local time zone of the browser by default. However Date is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD, using hyphens, or if it is YYYY-MM-DD HH:mm:ss, it will interpret it as local time. Unlike Date, moment will always be consistent about how it parses.
The correct way to parse an input moment as UTC in the format you provided would be like this:
moment.utc('07-18-2013', 'MM-DD-YYYY')
Refer to this documentation.
If you want to then format it differently for output, you would do this:
moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')
You do not need to call toString explicitly.
Note that it is very important to provide the input format. Without it, a date like 01-04-2013 might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.
use this :
return moment.utc(new Date(oData.CreatedAtUtc), 'MM/DD/YYYY h:mm A').local().format("YYYY-MM-DD HH:mm") + ' (' + timezoneAbbr + ')';

Categories