Displaying local time from ISO 8601 string with Momentjs - datetime

I want to display the local time from an ISO 8601 string using momentjs.
There is a discrepancy of minutes when I convert an ISO string using different date formats. If I use 'MM/DD/YYYY HH:mm', the minutes is correctly displayed. If I use 'ddd, MMM Do HH:MMa', 11 minutes is added (in my case).
My sample js (babel) code:
let today = moment('11/09/2016 00:00', 'MM/DD/YYYY HH:mm').toISOString();
//today = 2016-11-09T08:00:00.000Z
let formatted = moment(today, moment.ISO_8601).format('MM/DD/YYYY HH:mm');
//formatted = 11/09/2016 00:00
let formatted2 = moment(today, moment.ISO_8601).format('ddd, MMM Do HH:MMa');
//formatted2 = Wed, Nov 9th 00:11am
I would prefer using the second format. Can someone explain why there is a discrepancy?
Please see this fiddle: https://jsfiddle.net/anudhagat/8fgtjbc7/3/

I caught my silly mistake. I have capitalized the minutes in the second format, using MM makes it display months instead of minutes.

Related

MomentJS can't convert a date with format YYYY-MM-DD HH:mm:ss.fff Z

I am trying to convert the next date using MomentJS:
const moment = require('moment');
var datetime = "2017-11-19 02:45:22.011 +00:00";
var newDate = moment(datetime);
But it fails and the next message appears:
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.
Snippet showing the issue:
var datetime = "2017-11-19 02:45:22.011 +00:00";
var newDate = moment(datetime);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
I also tried using:
moment.utc(datetime);
but failed.
As moment(String) docs says:
When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found.
2017-11-19 02:45:22.011 +00:00 is not in ISO 8601 compliant format because there is a space between fractional seconds and UTC offset (2017-11-19 02:45:22.011+00:00 is an ISO 8601 version of your input). So you can use moment(String, String), here a live sample:
var datetime = "2017-11-19 02:45:22.011 +00:00";
var newDate = moment(datetime, 'YYYY-MM-DDTHH:mm:ss.fff Z');
console.log(newDate.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
Reformatting the date string from:
2017-11-19 02:45:22.011 +00:00
To:
2017-11-19T02:45:22.011Z
Solved it

Convert time by moment.js and timezone

I have a complicated problem with time converting;
I am coding by node.js and use moment, moment-jalaali and moment-timezone
I get a time from clinet in jalali format( example: 1396-03-03T23:00:00.00+04:30) to search and find some data before or after a time which is saved on UTC; My server has -04:00 zone;
var moment = require('moment');
var momentJalali = require('moment-jalaali');
var momentTZ = require('moment-timezone');
var jFormat = "jYYYY-jM-jD HH:mm:ss z";
var format = "YYYY-M-D HH:mm:ss z";
var toDate = momentJalali(req.body.toDate, jFormat).tz('UTC').format(format);
console.log("date: \n" + toDate "\n " + moment().format('Z') + "\n"); //output: date:
2017-5-25 03:00:00 UTC
-04:00
The response I expect is 2017-5-24 19:30:00 UTC; How could I reach that?
You do not need moment-timezone for this. Simply parse the input in UTC mode. Since you provided an offset, it will be taken into account automatically.
moment.utc("1396-03-03T23:00:00.00+04:30", "jYYYY-jMM-jDDTHH:mm:ss.SSZ")
.format("YYYY-MM-DD HH:mm:ss z")
//=> "2017-05-24 18:30:00 UTC"
Also note you had a few formatting tokens wrong - they are case-sensitive.
Additionally, I would seriously consider not using that particular input format if you have any control over it. By convention, it appears to be in ISO-8601 extended format, except that ISO-8601 is strictly bound to the proleptic Gregorian calendar. My understanding is that Jalaali dates are typically written as 1396/3/3 23:00:00, which would be jYYYY/jM/jD HH:mm:ss.
Also note that the value you asked for in your question is actually an hour off. your local time is 4.5 hours ahead of UTC so subtract: 23 - 4.5 = 18.5, thus 18:30 UTC, not 19:30 UTC.

Convert datepicker date to ISO format with moment.js

My task is to use a datepicker to pick a date in the prescribed format, eg(MM-DD-YYYY) and pass it to the server as ISO formatted.
While it test the output the ISO formatted date is one day behind.
For example
If i select
07-13-2015
My Output ISO format is
ISO format is :2015-07-12T18:30:00.000Z
Here you can see date is 13 but the output date is 12
I am from India. I tried with zone and utcOffset, ended up with no results. How do i set it right
Here is the JSFIDDLE
js code
$('#datetimepicker1').on("dp.change",function(e){
var selectedDate = $('#datetimepicker1').find("input").val();
selectedDate = moment(selectedDate,"MM-DD-YYYY");
$(".temp").text(moment(selectedDate).toISOString());
});
I do have a hidden field which value will be updated on change and that will be processed in the server. No issues on that.
$('#datetimepicker1').on("dp.change",function(e){
var selectedDate = $('#datetimepicker1').find("input").val();
selectedDate = moment(selectedDate,"MM-DD-YYYY");
$(".temp").text(selectedDate.toISOString());
});
Your selectedDate is already a moment object so you do not need to feed it back into another moment.
Example:
var test = '07-13-2015'
var mtest = moment(test,"MM-DD-YYYY")
mtest.toISOString()
"2015-07-13T06:00:00.000Z"
Your could try converting the date format to UTC at once.
selectedDate = moment(selectedDate).utc('MM-DD-YYYY')
According to http://dygraphs.com/date-formats.html, if you pass a string like '07-13-2015', it means Midnight of 13th July 2015. Now, if you use toISOString function, it will convert it to UTC by default. To not convert it to UTC, just pass a parameter true in the toISOString function. (Moment.js docs)
For example:
var date = '07-13-2015';
date = moment(date,'MM-DD-YYY');
console.log(date.toISOString(true));
This way, moment will not convert the date to UTC.

Need to format time zone offset using moment js

I have a datepicker on my page, when I select any date it produced a result something like
Sun Sep 07 2014 00:00:00 GMT+0500 (Pakistan Standard Time)
And I need to format it: YYYY-MM-DDTHH:mm:ss Z
So, for this I use moment syntax
var date='Sun Sep 07 2014 00:00:00 GMT+0500 (Pakistan Standard Time)';
moment(date).format('YYYY-MM-DDTHH:mm:ss Z');
which produces an output
2014-09-07T00:00:00 +05:00
That's good, but my api expect standard timezone offset 'Z' instead of parsing into local current time zone (i.e +5:00) in my case.
So, I want to produce this
2014-09-07T00:00:00Z
How is it possible?
Use moment.utc() to display time in UTC time instead of local time:
var dateValue = moment(date).utc().format('YYYY-MM-DDTHH:mm:ss') + 'Z';
or moment().toISOString() to display a string in ISO format (format: YYYY-MM-DDTHH:mm:ss.sssZ, the timezone is always UTC):
var dateValue = moment(date).toISOString();
JSFiddle
Rather than using a hard-coded format string and then concatenating the 'Z' after it, it would be better to just use the toJSON() function which has been around since moment js v2.0. Like so:
moment('Sun Sep 07 2014 00:00:00 GMT+0500 (Pakistan Standard Time)').toJSON();
Here's the complete JSFiddle.

ColdFusion: Error Passing Date that doesn't have day of week?

I am trying to parse two date strings into date objects. The code works for one string, but throws an "invalid date time" error for the other. The only difference is that it's got a "Sat, " at the beginning! Please tell me why this is happening and how I can solve it!
<cfset datetimetest1 = "23 Nov 2013 00:53:12 +0000">
<!--- ^ This throws an error (when you try to pass it). Error says 'invalid date time' --->
<cfset datetimetest2 = "Sat, 23 Nov 2013 00:53:12 +0000">
<!--- ^ This works when it is parsed --->
<cfoutput>
#parsedatetime(datetimetest1)# #parsedatetime(datetimetest2)#
</cfoutput>
I identified RSS dates that are being used from the following sources and tested them against isDate(), DateFormat() and LSDateFormat(). ColdFusion 10,286680 was only able to parse 65% of the dates (38 out of 58).
http://rssdateformats.tumblr.com/
https://github.com/mjibson/goread/blob/0387db10bd9fd9ccd90d557fa30b6e494efa577a/goapp/utils.go#L129
Here's the test script that I wrote:
https://gist.github.com/JamoCA/7617349
I've been looking for a Java date parser library and recently found Natty and StringToTime, but haven't used either yet. (Neither resource provides a downloadable JAR file.):
http://natty.joestelmach.com/
https://github.com/collegeman/stringtotime
Update:
As of CF10+, you can use a custom format string to instruct the function on how to parse and convert the input into a datetime object:
// Custom format string
dateObject = parseDateTime("23 Nov 2013 00:53:12 +0000"
, "dd MMM yyyy HH:mm:ss zzz");
This is one area in which CF's flexibility and ease of use can be a disadvantage IMO. Unfortunately parseDateTime does not allow you specify the format of the input string, so CF has to do a lot of guessing to "automagically" convert your string into a date object.
One of the tools CF employs is java's SimpleDateFormat class, which utilizes patterns to parse or convert strings into Dates. My understanding is CF maintains a listing of standard date/time patterns (according to U.S. date conventions). Your first string must not match any of those patterns. Hence the error.
If your date strings are always in UTC, you could simply use list functions to omit the timezone offset ie +0000, then parse the string as usual:
<cfscript>
origString = "23 Nov 2013 00:53:12 +0000";
dateString = listFirst(origString, "+");
WriteDump(parseDateTime(dateString));
</cfscript>
Or you could DIY using SimpleDateFormat and the appropriate pattern dd MMM yyyy HH:mm:ss Z (see Date and Time Patterns). Just note the returned dates are in local time, so you may need to use DateConvert if you want UTC times:
// get formatter based on default locale
formatter = createObject("java", "java.text.SimpleDateFormat").init();
// set up pattern for input date string
formatter.applyPattern("dd MMM yyyy HH:mm:ss Z");
// parse it into a date object
dateObject = formatter.parse("23 Nov 2013 00:53:12 +0000");
// display result in local and UTC time
WriteDump("local="& dateObject);
WriteDump("utc="& DateConvert("local2UTC", dateObject));

Resources