Using Moment to Validate Default Javascript Date Format - javascript

I want to use moment (or any other method) to validate a particular string as a valid date value based on the default javascript date format.
I have the following code:
var date = new Date(); // Tue Nov 28 2017 17:54:41 GMT-0600 (CST)
I want to take that string output and use moment to validate that as a valid date string. I know I can do this:
moment(date, moment.ISO_8601).isValid();
But there is a problem. Here are the results for the same date values:
moment(new Date(), moment.ISO_8601).isValid(); //True
moment("Tue Nov 28 2017 17:54:41 GMT-0600 (CST)", moment.ISO_8601).isValid() //False
Which is not what I want since both of them should be true. I can't do new Date(...) because here's the results for that approach:
moment(new Date("Tue Nov 28 2017 17:54:41 GMT-0600 (CST)"), moment.ISO_8601).isValid(); //True
moment(new Date("3"), moment.ISO_8601).isValid(); //True
This also is not what I want since the second line should be false.
How do I properly valid a string as a valid date only if it strictly follows the format Tue Nov 28 2017 17:54:41 GMT-0600 (CST)?
I have researched everywhere to understand what format Tue Nov 28 2017 17:54:41 GMT-0600 (CST) is but I can't find anything. It's not ISO 8601 and not RFC 2822 either.

As RobG stated in the comments There is no "default javascript date format". The output from Date.prototype.toString is implementation dependent
Since your input is neither in ISO 8601 nor in RFC 2822 Date time formats you have to use moment(String, String) using 'ddd MMM D YYYY HH:mm:ss [GMT]Z' as format parameter. If you want that your string matches strictly your format, you can use strict mode (moment(String, String, Boolean)).
Please note that moment does not provide token for parsing timezone abbreviation (e.g. CST), so your input will not be recognized in strict mode. Here an example of parsing using both strict and forgiving mode; myIsValid function is an example of removing timezone abbreviation from the input.
var s = 'Tue Nov 28 2017 17:54:41 GMT-0600 (CST)';
var fmt = 'ddd MMM D YYYY HH:mm:ss [GMT]Z';
console.log(moment(s, fmt).isValid());
console.log(moment(s, fmt, true).isValid());
function myIsValid(input){
// Check if input contains ()
var idxl = input.indexOf('(');
var idxr = input.indexOf(')');
if( idxl>0 && idxr>0 ){
// Remove timezone abbreviation
input = input.substr(0, idxl-1);
}
var fmt = 'ddd MMM D YYYY HH:mm:ss [GMT]Z';
return moment(input, fmt, true).isValid();
}
console.log(myIsValid(s));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Lastest version of moment (2.19.2), gives Invalid Date even with forgiving mode. Using parsingFlags() you see that weekdayMismatch is true, I think this is an issue of the 2.19+ version of moment this is related to moment #4227 issue.
var s = 'Tue Nov 28 2017 17:54:41 GMT-0600 (CST)';
var fmt = 'ddd MMM D YYYY HH:mm:ss [GMT]Z';
var m1 = moment(s, fmt);
var m2 = moment(s, fmt, true);
console.log(m1.isValid());
console.log(m1.parsingFlags());
console.log(m2.isValid());
console.log(m2.parsingFlags());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>

If you want to strictly validate a timestamp with Moment.js, use the strict flag when parsing:
var s = 'Tue Nov 28 2017 17:54:41 GMT-0600';
s = s.replace('GMT','');
console.log('Modified string: ' + s);
var mStrict = moment(s, 'ddd MMM D YYYY HH:mm:ss ZZ', true);
console.log('Strict parse: ' + mStrict.format());
var mLoose = moment(s, 'ddd MMM D YYYY HH:mm:ss ZZ');
console.log('Loose parse : ' + mLoose.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>
However, for me both strict and loose produce "Invalid date", which is incorrect (and should be "Invalid Date"). The issue seems to be the timezone value or token.

Related

How to change ISO date to Standard JS Date?

I am trying to change an ISO date to a Standard JS Date format. The JS format I am referring to is:
Mon `Jul 20 2020 14:29:52 GMT-0500 (Central Daylight Time)`
What is the best way to go about doing this? Thanks!
const ISO_DATE = '2020-07-14T23:02:27.713Z';
function formatDate(dateStr) {
const date = new Date(dateStr);
return date.toString();
};
console.log(formatDate(ISO_DATE));
One way is:
let isoDate = "2020-07-20T14:29:52Z";
var myDate = new Date(isoDate);
console.log(myDate.toString()); // Mon Jul 20 2020 17:29:52 GMT+0300 ( (your time zone)
console.log("Back to ISO Date: ", myDate .toISOString());
If you want to convert it back to ISO Date use:
console.log(myDate.toISOString());

Format the current date and time using momentjs

I want to convert the current date and time to in the following way using moment.js.
Current date and time using javascript new Date(): Thu Jul 12 2018 09:28:51 GMT+0530 (India Standard Time) and want to convert the above format to below mentioned format.
1. Thu, 12 Jul 2018 09:31:37 GMT
2. 2018-07-12T09:31:38Z
You can learn more about formatting with moment.js here.
Escape words in formatting with escaping-characters "[]".
console.log(moment());
console.log(moment().format('ddd, DD MMM YYYY HH:mm:ss [GMT]'));
console.log(moment().format('YYYY-MM-DD[T]HH:mm:ss[Z]'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
you can also try like below for
nodejs
var moment = require('moment');
var format1 = moment().utcOffset(330).format('ddd, DD MMM YYYY HH:mm:ss [GMT]')
var format2 = moment().toDate();
console.log(format1);
console.log(format2);
angular
import moment from 'moment';
var format1 = moment().utcOffset(330).format('ddd, DD MMM YYYY HH:mm:ss [GMT]')
var format2 = moment().toDate();
console.log(format1);
console.log(format2);
Install moment like below
npm install --save moment
Html javascript
var format1 = moment().utcOffset(330).format('ddd, DD MMM YYYY HH:mm:ss [GMT]')
var format2 = moment().toDate();
console.log(format1);
console.log(format2);
moment source script
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
You can use toGMTSting method to convert local time into GMT format. Hope this helps..
console.log(new Date().toGMTString());
console.log(new Date("Fri Jan 20 2012 11:51:36 GMT-0530").toGMTString());
You can try these also:
var moment = require('moment');
let startDate= new moment('11/22/1990','MM/DD/YYYY').format("YYYY/MM/DD");
You can also understand these:
let otherDate= 1399919400000;
var neweDate = moment(otherDate).format('DD/MM/YYYY');
//My neweDate output is "13/05/2014";
moment.locale('cs');
console.log(moment.locale()); // en
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
You can verify the date also:
moment("not a real date").isValid(); // false
moment("2010 13", "YYYY MM").isValid(); // false (not a real month)
moment("2010 11 31", "YYYY MM DD").isValid(); // false (not a real day)
moment("2010 2 29", "YYYY MM DD").isValid(); // false (not a leap year)
moment("2010 notamonth 29", "YYYY MMM DD").isValid(); // false (not a real month name)
You can create a Moment with a pre-existing native Javascript Date object.
var day = new Date(2011, 9, 16);
var dayWrapper = moment(day);
You can create a moment with an array of numbers that mirror the parameters passed to new Date()
[year, month, day, hour, minute, second, millisecond]
moment([2010, 1, 14, 15, 25, 50, 125]); // February 14th, 3:25:50.125 PM
Any value past the year is optional, and will default to the lowest possible number.
moment([2010]); // January 1st
moment([2010, 6]); // July 1st
moment([2010, 6, 10]); // July 10th

Format date using moment.js

I'm using the moment.js library to format dates in the format MM DD, YYYY. What am I missing?
Code below:
import moment from 'moment';
var dateStr = '2015-10-19T13:33:52.140Z';
var d = new Date(dateStr); // Mon Oct 19 2015 13:33:52 GMT+0000 (GMT)
console.log( moment(d, "MM DD, YYYY").toDate() ) // Still outputs Mon Oct 19 2015 13:33:52 GMT+0000 (GMT)
There is no need tou use JavaScript Date to parse your string, just use moment(string) (because your input is in ISO 8001 format), then you have to use format():
var dateStr = '2015-10-19T13:33:52.140Z';
console.log( moment(dateStr).format("MM DD, YYYY"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Simply use the Format method
moment(dateStr).format("MM DD, YYYY");

Javascript Date() in ReactJS: How to accept input as GMT/UTC and convert it into ISO string?

Currently the input is "12 09 2016 00:00:00" and should assume it is in inputted as GMT date and time. But rather, it accepts it as local and converts it as such. And when it is turned to ISOString(), it converts it to GMT, and adds the time difference.
How can I take an input in "12 09 2016 00:00:00" format, take it as GMT/UTC, and do .toISOString() to turn it into the ISO format, "2016-12-09T00:00:00.000Z"?
var dateAndTime = new Date("12 09 2016 00:00:00")
//Returns: "Fri Dec 09 2016 00:00:00 GMT-0800 (PST)"
//Want it to return: "Fri Dec 09 2016 00:00:00 (GMT)"
var gmtDateAndTime = dateAndTime.toISOString();
//Returns: "2016-12-09T08:00:00.000Z"
//Want it to return: "2016-12-09T00:00:00.000Z"
Thank you and will be sure to vote up and accept the answer.
How can I take an input in "12 09 2016 00:00:00" format, take it as
GMT/UTC, and do .toISOString() to turn it into the ISO format,
"2016-12-09T00:00:00.000Z"?
It seems you just want to reformat the string, so just do that:
// Reformat string in MM DD YYYY HH:mm:ss format to
// ISO 8601 UTC
function formatDateStringISO(s) {
var b = s.split(/\D/);
return b[2] + '-' + b[0] + '-' + b[1] +
'T' + b[3] + ':' + b[4] + ':' + b[5] + '.000Z';
}
console.log(formatDateStringISO('12 09 2016 00:00:00'))
If you want to parse the string to a Date then output an ISO 8601 format string, do that:
// Parse string in MM DD YYYY HH:mm:ss format
// If date string is invalid, returns an invalid Date
function parseDateAsUTC(s) {
var b = s.split(/\D/);
var d = new Date(Date.UTC(b[2], --b[0], b[1], b[3], b[4], b[5]));
// Validate date
return d && d.getMonth() == b[0]? d : new Date(NaN);
}
// Valid date Invalid date
['12 09 2016 00:00:00', '12 34 2016 00:00:00'].forEach(function(s) {
var d = parseDateAsUTC(s);
console.log(s + ' => ' + d[isNaN(d)? 'toString' : 'toISOString']());
});
You need to use another Date constructor. The default constructor creates time in your local timezone.
Replace this:
var dateAndTime = new Date("12 09 2016 00:00:00")
With this:
var dateAndTime = new Date(Date.UTC(2016, 09, 12, 0, 0, 0));
If you can't convert your string ("12 09 2016 00:00:00") manually to the individual UTC parameters, you can use this (but unreliable especially in IE):
var utcDate = Date.parse("12 09 2016 00:00:00");
Do not use Date to parse happenstance date strings. Date.parse only works in a well defined manner when the input is an ISO8061 string.
From "15.9.4.2 Date.parse" in the ECMA 5 standard:
The function first attempts to parse the format of the String according to the rules called out in Date Time String Format (15.9.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
and from 15.9.1.15 the string format recognized is
YYYY-MM-DDTHH:mm:ss.sssZ
which looks very much the ISO string you want to arrive at, not start with.
Alternative choices to solve the issue might include:
write your own function to parse a user input string. Has the problem that "12 09 2016" could mean "Dec 9 2016" or "Sep 12 2016" depending on user locale.
Use a date and time library. Moment.js is frequently mentioned in SO answers regarding such libraries.
Use the output of a date picker or validated data from a data base. Avoids issues with locale dependent formats.
Hard code conversion to ISO8061 format without parsing may be an option if the input string is absolutely guaranteed to be in "mm dd yyyy hh:mm:ss" format, as for example using
function isoFromZ( str) {
return str.substr(6,4) + "-" +
str.substr(0,2) + "-" +
str.substr(3,2) + "T" +
str.substring(11) + ".000Z";
}
In summary extract the UTC date and time components from a custom input string before creating a Date object. If extraction produced an ISO8061 date string it can be passed directly to the Date constructor as a parameter.

Moment.js - How to convert date string into date?

Following up from my previous post: Javascript Safari: new Date() with strings returns invalid date when typed
I am using Moment.js to convert a date string into a date field based on user input in the text box.
This is to prevent the problem I described in the linked post for Safari and Firefox not able to render the date when Chrome is fine.
Here is the code snipper:
var tempDate = moment(userInputFieldDate).format('DD-MM-YYYY');
alert(tempDate);
In Chrome, it does work fine (it use to work with the Javascript Date object too) but gives me the moment.js deprecation warning
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.
Arguments: [object Object]
Error
On Firefox and Safari is just gives an UNDEFINED DATE in the alert window. So not entirely sure what should I be doing to convert the date string to a Date object.
Any suggestions on this issue?
If you are getting a JS based date String then first use the new Date(String) constructor and then pass the Date object to the moment method. Like:
var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
In case dateString is 15-07-2016, then you should use the moment(date:String, format:String) method
var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
Sweet and Simple!
moment('2020-12-04T09:52:03.915Z').format('lll');
Dec 4, 2020 4:58 PM
OtherFormats
moment.locale(); // en
moment().format('LT'); // 4:59 PM
moment().format('LTS'); // 4:59:47 PM
moment().format('L'); // 12/08/2020
moment().format('l'); // 12/8/2020
moment().format('LL'); // December 8, 2020
moment().format('ll'); // Dec 8, 2020
moment().format('LLL'); // December 8, 2020 4:59 PM
moment().format('lll'); // Dec 8, 2020 4:59 PM
moment().format('LLLL'); // Tuesday, December 8, 2020 4:59 PM
moment().format('llll'); // Tue, Dec 8, 2020 4:59 PM
if you have a string of date, then you should try this.
const FORMAT = "YYYY ddd MMM DD HH:mm";
const theDate = moment("2019 Tue Apr 09 13:30", FORMAT);
// Tue Apr 09 2019 13:30:00 GMT+0300
const theDate1 = moment("2019 Tue Apr 09 13:30", FORMAT).format('LL')
// April 9, 2019
or try this :
const theDate1 = moment("2019 Tue Apr 09 13:30").format(FORMAT);

Categories

Resources