Issue with using moment.js - momentjs

I was creating project in Angular and to format date I decided to use moment.js. But the problem is from the backend I get such format "2020-02-06" thus I decided to use 'MMM DD, YYYY' and I want "2020-02-06" to look like Feb 6, 2020 with this format MMM DD, YYYY. So, to achieve that I have this code
moment(
response.data.projectCreatedDate //this contains "2020-02-06"
).format("MMM DD, YYYY");
BUT the problem is instead of getting Feb 6, 2020 I get 13 May, 2020 which is today's date. Pls can you help, what am I doing wrong?

Moment with empty argument returns current date, and format on top of it returns current formatted date .Your date from server might be undefined, Hence you are the getting current date formatted.
You can also pass custom date for formatting too!
//Formatting an input date
var str = "2020-02-06";
console.log(moment(str, "YYYY-MM-DD").format("MMM D,YYYY"));
//Formatting current date
console.log('Current Date: ', moment().format("MMM D,YYYY"));
//Formatting array of dates
var arr = ["2020-02-06", "2020-01-13"];
var res = arr.map(date => {
return moment(date, "YYYY-MM-DD").format("MMM D,YYYY");
});
console.log(res);
<script src="https://momentjs.com/downloads/moment.js"></script>

Nothing is wrong with moment here, you are getting an empty response inside response.data.projectCreatedDate from your server.
moment("2020-02-06").format("MMM DD, YYYY") //Feb 06, 2020
moment().format("MMM DD, YYYY") //todays date.
Thanks.

Related

Displaying local time from ISO 8601 string with Momentjs

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.

moment toISOstring without modifying date

I have a date like "Thu Sep 01 2016 00:00:00 GMT+0530 (IST)" which I need to send to server as ISO-8601 utc time. I tried like :
moment(mydate).toISOString()
moment.utc(mydate).toISOString()
moment(mydate).utcOffset("+00:00").toISOString()
but I am getting the result like
2016-08-31T18:30:00.000Z
which is 1day behind my intended time. So what can I do to make moment ignore my local timezone and see it as UTC?
Edit:
The expected output is
2016-09-01T18:30:00.000Z
And no, the initial input isn't a string rather a javascript "new Date()" value.
Reason this happens:
This happens because .toISOString() returns a timestamp in UTC, even if the moment in question is in local mode. This is done to provide consistency with the specification for native JavaScript Date .toISOString()
Solution:
Use the same function and pass true value to it. This will prevent UTC Conversion.
moment(date).toISOString(true)
const date = new Date("2020-12-17T03:24:00");
const dateISOStringUTC = moment(date).toISOString();
const dateISOString = moment(date).toISOString(true);
console.log("Converted to UTC:" + dateISOStringUTC)
console.log("Actual Date value:" + dateISOString)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
I take the same problem today and find the solution.
Here is the solution: moment(date,moment.ISO_8601)
var date = new Date();
console.log("Original Date");
console.log(date);
console.log("After Moment Format");
console.log(moment(date,moment.ISO_8601));
Test Execution:
Moment Documentation: MomentJs

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.

IE JavaScript date parsing error

Why cannot IE parse this string as a Date object.
var d = Date.parse("Fri Jun 11 04:55:12 +0000 2010"); // returns NaN
However, it works well in FireFox. I am running IE 8.
Thanks.
You are getting NaN value in IE 8 and its working in Firefox because the format of the string varies with browser and operating system.
For example, in IE6 for Windows XP, the string is in the following format:
Tue Dec 05 16:47:20 CDT 2006
But in Firefox for Windows XP, the string is
Tue Dec 05 2006 16:47:20 GMT-0500
to make it compatible with both browser you will have to first check the browser in your
javascript code and then accordingly give your input date string.
I've found the jQuery Globalization Plugin date parsing to work best. Other methods had cross-browser issues and stuff like date.js had not been updated in quite a while.
You also don't need a datePicker on the page. You can just call something similar to the example given in the docs:
$.datepicker.parseDate('yy-mm-dd', '2007-01-26');
Is solved my problem by creating an date object and let me give it back the timestamp.
But for this you need to convert you string into this format:
year, month, date, hours, minutes, seconds,ms
an example would be like:
dateObj = new Date(year, month, date);
timestamp = dateObj.getTime();
This works save in IE and FF.
IE Dev Center: Date Object (JavaScript)
Mozilla Dev Network: Date
For your example you would to something like this:
//your string
var str = "Fri Jun 11 04:55:12 +0000 2010";
//maps months to integer from 0 to 11
var monthArray = {"Jan":0, "Feb":1, "Mar":2, "Apr":3, "May":4, "Jun":5, "Jul":6, "Aug":7, "Sep":8, "Oct":9, "Nev":10, "Dec":11};
//get the values from the string
var regex = /^[^ ]+ ([^ ]+) (\d{1,2}) (\d{2}):(\d{2}):(\d{2}) \+(\d{4}) (\d{4})$/;
match = regex.exec(str);
var month = monthArray[match[1]],
date = match[2],
hours = match[3],
minutes = match[4],
seconds = match[5],
ms = match[6],
year = match[7];
//create date object with values
var dateObject = new Date(year, month, date, hours, minutes , seconds, ms);
var ts = dateObject.getTime(); //timestamp in ms
Problem
In case your date is stored in SQL datetime like 2020-04-07 05:30:00 and want to parse it in IE. When you parse it with JavaScript in IE using new Date(), it outputs Invalid Date while latest versions of Chrome and Firefox parse this date correctly.
Solution
You have to replace <space> with T in datetime string coming from SQL.
Example
let myDate = '2020-04-07 05:30:00';
let myFormattedDate = myDate.replace(' ', 'T'); // '2020-04-07T05:30:00'
console.log(new Date(myFormattedDate));
because of the +00000. try to add that the last
var d = Date.parse("Fri Jun 11 04:55:12 2010 +0000");
This may help you. I just solved a problem similar to this.
Problem with Javascript Date function in IE 7, returns NaN

Javascript Date Validation

How to validate particular format date string using Javascript?
I have one date picker which has the display format like "dddd MMMM dd, yyyy"(displaying like this:"Wednesday February 03, 2010".) So i have to validate this format using javascript. Please help me for implementing this..
If you want to check exactly that format, you could use regular expression:
var re = new RegExp( '^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)\\s*(January|February|March|April|May|June|July|August|September|November|December)\\s*(\\d\\d),\\s*(\\d{2,4})$' );
var date = 'Wednesday February 03, 2010';
if ( ( match = date.match( re ) ) != null )
{ // valid
alert( match );
}
Or if you just need to know if it is a valid date, what format ever, simply convert it:
var dateSec, dateObj, dateStr = 'Wednesday February 03, 2010';
dateSec = Date.parse( dateStr ); // unix timestamp
if ( dateSec ) // not NaN
dateObj = new Date( dateSec ); // date object
If your application is going to require date manipulation methods, you may want to consider using something like the Datejs library.
If you opt for Datejs, you can use the parseExact() method for the validation. It will return a date object if the date is valid, or null if the date is invalid.
Native JavaScript support for date formatting and validation is somewhat limited.
Take a look at http://www.datejs.com/
You can do stuff like Date.parse('my date string')
Datejs or Dojo can do this. With dojo.date.locale.parse:
var dateAsString = "Wednesday February 03, 2010";
var dateObject = dojo.date.locale.parse(dateAsString, {datePattern: "EEEE MMMM dd, yyyy", selector: "date", locale: "en"});
dateObject will contain the Date object, or null if the string does not match the specified pattern. This can work with a fixed language or any native language.
It doesn't seem right that a date picker would use this as a serialized Date format, though. It should use something easier to parse, like ISO8601 representation.

Resources