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

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);

Related

I need correct time from `1609891200000` without using Moment

var now = moment(1609891200000, "x").format('MMM DD h:mm A');
var x = new Date(1609891200000);
console.log(now); // Prints Jan 06 12:00 AM
console.log(x.toLocaleTimeString()); // Prints 05:30:00
I don't know why I keep getting 5:30 as time. I need a way to get the correct time i.e 12:00 AM without the use of Moment.
How can I do this?
You should provide a code of time zone,
If there is no code, then it will provide by default
var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
// toLocaleTimeString() without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(date.toLocaleTimeString());
// → "7:00:00 PM" if run in en-US locale with time zone America/Los_Angeles
Instead, you can use
var x = new Date(1609891200000);
x.toGMTString() // "Wed, 06 Jan 2021 00:00:00 GMT"
x.toUTCString() // "Wed, 06 Jan 2021 00:00:00 GMT"
x.toISOString() // "2021-01-06T00:00:00.000Z"

Using Moment to Validate Default Javascript Date Format

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.

momentJS convert possibility day into Date() js format

I am trying to convert a date in format momentjs into a date from javascript native new Date().
The problem is that if I have moment(myDay).toDate(); it converts to the current date, and I want the date from myDay.
myDay looks like: "YYYY-MM-DD" => 2017-11-24 and I would like to have it with the format: Fri Nov 24 2017 20:17:11 GMT+0100 (Hora estándar romance) but I get Thu Nov 16 2017 etc...
It is possible to convert it like that way?
Don't need moment:
let [yr, mn, day] = myDay.split('-').map(Number);
// note that JS months are 0-11 not 1-12
let datestr = new Date(yr, mn - 1, dy).toString();
console.log(datestr); // "Fri Nov 24 2017 00:00:00 GMT-0500 (EST)"
you want something like this:
moment(myDay, "YYYY-MM-DD").toString();
moment().toString() Returns an english string in a similar format to JS Date's .toString().
moment().toString() // "Sat Apr 30 2016 16:59:46 GMT-0500"

If statement with date comparison

I'm trying to write an if statement that runs some code if the date is after April 24th, 2017, 10 am EDT, but it doesn't appear that my variables are comparable (different data types?).
I'm trying to avoid using Moment.js for just this.
var today = new Date();
var launch = 'Mon Apr 24 2017 10:00:00 GMT-0400 (EDT)';
today returns Tue Apr 04 2017 14:34:41 GMT-0400 (EDT).
When I test if either is greater than the other, both are false. How should I format my dates?
Thanks!
You have to have launch as a date type:
var today = new Date();
var launch = 'Mon Apr 24 2017 10:00:00 GMT-0400 (EDT)';
var launchDate = Date.parse(launch);
if ( launchDate > today )
You should also read more about dates here:
Compare two dates with JavaScript

date string that will ignore timezone offset

I am at (UTS-05:00) Eastern Time (US & Canada)
i.e, new Date().getTimezoneOffset() == 300 seconds.
Now, I have a API endpoint (JSON) that returns a date string like this.
{
someDate: '2016-01-01T00:40:00.000+00:00'
}
Here, I pass it to Date constructor like this
var dateString = "2016-01-01T00:40:00.000+00:00";
var someDay = new Date(dateString);
console.log(someDay)
Mozilla Firefox console shows
Date {Fri Jan 01 2016 00:40:00 GMT-0500 (Eastern Summer Time)}
Google Chrome console shows
Thu Dec 31 2015 19:40:00 GMT-0500 (Eastern Standard Time)
Chrome is taking the TimezoneOffset into consideration and Firefox is not. What can I do to get a Date that doesn't take Offset into consideration like FireFox in Chrome?
You can do it by:
var dates = '2016-01-01T00:40:00.000+00:00'.split(/-|T|:/);
var newDate = new Date(dates[0], dates[1]-1, dates[2], dates[3], dates[4]);
This hack works (not very clean, but does the job)
var dateString = '2016-07-27T01:40:30';
var dateParts = dateString.split(/-|T|:/);
var saneDate = new Date(
+dateParts[0],
dateParts[1] - 1,
+dateParts[2],
+dateParts[3],
+dateParts[4],
+dateParts[5]);
console.log(saneDate);

Categories

Resources