Format the current date and time using momentjs - javascript

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

Related

Moment.js conversion of RFC2822 date

I have a date as '04 FEB 1994' which I'm trying to convert into a date object for comparison.
I've tried a whole bunch of variations, the current one is...
var trydate = moment(licDob, "DD-MMM-YYYY");
var momentObj = moment(trydate);
var momentString = momentObj.format('YYYY-MM-DD');
where licDob is 04 FEB 1994. momentObj is coming back as 853506000000 which makes momentString 1997-01-18.
Guidance much appreciated.
use
var newTry = moment(licDob,'DD MMM YYYY').toDate()
considering you want to convert it to Date()
You were close the the right solution. You have to use the moment constructor with 2 parameters. The 1st parameter is your string date and the 2nd is the format.
In your case the correct format is DD MMM YYYY
const stringDate = "04 FEB 1994";
const momentDate = moment(stringDate, "DD MMM YYYY");
console.log("Formatted:", momentDate.format("DD/MM/YYYY"));
console.log("EPOCH:", momentDate.valueOf())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

UNIX timestamp of date on midnight UTC+0

I have the following date: 07/08/2018 in the format m/d/Y. This date is july 08, 2018.
And I have the following JavaScript code:
var dateFrom = '07/08/2018';
dateFrom = new Date(dateFrom);
alert(dateFrom);
When I do this, I get the following result:
Sun Jul 08 2018 00:00:00 GMT+0200 (Midden-Europese zomertijd)
As you can see, because I live in Belgium, I get the time + GMT+2. But that's not what I want. I want the exact UNIX timestamp of 07/08/2018 (or any other date) of GMT+0.
I have the following JavaScript code:
var dateFrom = '07/08/2018';
dateFrom = Math.floor((new Date(dateFrom)).getTime()/1000);
alert(dateFrom);
If I execute this code, I get the following result:
1531000800
But that's not what I want. If I check the UNIX timestamp I get (1531000800) on this (https://www.unixtimestamp.com/index.php) website, I get the following result:
1531000800
Is equivalent to:
07/07/2018 # 10:00pm (UTC)
I want the UNIX timestamp that is equal to 07/08/2018 # 00:00am (UTC).
How can I achieve this?
Thanks in advance!
As per the MDM documentation:
The following statement creates a Date object using UTC instead of local time:
var utcDate = new Date(Date.UTC(2018, 11, 1, 0, 0, 0));
Code Sample:
var date = new Date()
var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()))
console.log(date)
console.log(utcDate)

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.

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

Regarding JavaScript new Date() and Date.parse()

var exampleDate='23-12-2010 23:12:00';
I want to convert above string into a date and have tried a couple things:
var date = new Date(exampleDate); //returns invalid Date
var date1 = Date.parse(exampleDate); //returns NAN
This code is running fine in IE and Opera, but date is returning me an invalid Date and date1 is returning NAN in Firefox. What should I do?
The string in your example is not in any of the standard formats recognized by browsers. The ECMAScript specification requires browsers to be able to parse only one standard format:
The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ
This format includes date-only forms:
YYYY
YYYY-MM
YYYY-MM-DD
It also includes time-only forms with an optional time zone offset appended:
THH:mm
THH:mm:ss
THH:mm:ss.sss
Also included are “date-times” which may be any combination of the above.
If the String does not conform to that format the function may fall back to any
implementation-specific heuristics or implementation-specific date formats. Unrecognizable Strings or dates
containing illegal element values in the format String shall cause Date.parse to return NaN.
So in your example, using 2010-12-23T23:12:00 is the only string guaranteed to work. In practice, most browsers also allow dates of the format DD Month YYYY or Month DD, YYYY, so strings like 23 Dec 2010 and Dec 23, 2010 could also work.
Above format is only supported in IE and Chrome.
so try with another formats. following are some formats and there supporting browsers.
<script type="text/javascript">
//var dateString = "03/20/2008"; // mm/dd/yyyy [IE, FF]
var dateString = "2008/03/20"; // yyyy/mm/dd [IE, FF]
// var dateString = "03-20-2008"; // mm-dd-yyyy [IE, Chrome]
// var dateString = "March 20, 2008"; // mmmm dd, yyyy [IE, FF]
// var dateString = "Mar 20, 2008"; // mmm dd, yyyy [IE, FF]
// Initalize the Date object by passing the date string variable
var myDate = new Date(dateString);
alert(myDate);
</script>
You could parse it manually with a regular expression then call the date constructor with the date elements, as such:
var parseDate = function(s) {
var re = /^(\d\d)-(\d\d)-(\d{4}) (\d\d):(\d\d):(\d\d)$/;
var m = re.exec(s);
return m ? new Date(m[3], m[2]-1, m[1], m[4], m[5], m[6]) : null;
};
var dateStr = '23-12-2010 23:12:00';
parseDate(dateStr).toString(); //=> Thu Dec 23 2010 23:12:00 GMT-0800
JavaScript should support conversion at least from the following dateStrings:
* yyyy/MM/dd
* MM/dd/yyyy
* MMMM dd, yyyy
* MMM dd, yyyy
Try with:
var exampleDate='12/23/2010 23:12:00';
var date = new Date(exampleDate);
Use datejs and this code:
var exampleDate='23-12-2010 23:12:00';
var myDate = Date.parseExact(exampleDate, 'dd-MM-yyyy hh:mm:ss');
myDate should be a correctly constructed Date object.
Just use in this format:
var exampleDate='2010-12-23 23:12:00';
#casablanca has a good answer but it's been 10+ years and this still has a lot of weight in Google so I thought I'd update with a new answer.
TL;DR
// Use an ISO or Unix time string to generate `Month DD, YYYY`
const newDate = new Date('23-12-2010')
const simpleDate = `${newDate.toLocaleString('en-us', { month: 'long' } )} ${newDate.getDate()}, ${newDate.getFullYear()}`
// yields: December, 23 2010 (if you want date suffix, read until the end)
Background: Dates come in a lot of formats, but you're mostly going to receive:
An ISO 8601 format date (YYYY-MM-DDTHH:mm:ss.sssZ) where Z is a UTC timezone offset. You might also get a subset of this (ie, YYYY-MM-DD)
Unix timestamp format date (1539734400), where the number is literally the total amount of milliseconds since the beginning of Unix time, Jan 1st 1970.
Basics: JS has a built-in Date prototype that accepts ISO 8601 and derivatives (of just time or just date). You can instantiate with new Date and return a date object OR you can use the Date.parse() method to return a Unix timestamp.
const dateObj = new Date('23-12-2010:23:12:00') // returns date object
const dateDateOnly = new Date('23-12-2010') // returns date object
const dateTimeOnly = new Date('23:12:00') // returns date object
const dateString = Date.parse('23-12-2010:23:12:00') // returns Unix timestamp string
You can also break the date into 7 parameters: the year, the month (starting from 0), the day, the hour, the minutes, seconds and milliseconds with the time zone offset - NOTE, I've used the multi-params approach only once in my career. Since I'm in Texas I get, UTC-5 (Central Time) when I run the following:
const dateByParam = new Date(2021, 2, 26, 13, 50, 13, 30) // Fri Mar 26 2021 13:50:13 GMT-0500 (Central Daylight Time)
New-ish Stuff toLocaleString: Typically, the return from the Date object is still pretty dense like our last example (Fri Mar 26 2021 13:50:13 GMT-0500 (Central Daylight Time) so additional methods have been added to help developers.
Typically with a date, I want something like March 21st, 2021 - the day and year have been easy to get for a long time:
// Assuming myDate is a JS Date object...
myDate.getDate() // date on the calendar, ie 22
myDate.getDay() // day of the week, where 0 means Sunday, 1 means monday, etc
myDate.getFullYear() // 4 digit year, ie, 2021
But I've always had to build a function to turn getDay into January, February, March, not anymore. toLocaleString() gives you some new superpowers. You can pass it two params, a string for region (ie, en-us) and an object with what you want back (ie, { month: 'long' }). This helps internationalize the response, if need be.
// Again, assuming myDate is a JS Date object...
myDate.toLocaleString('en-us', { month: 'long' } ) // March
Date Suffix I've still seen no built-in way to get the suffix for a date, like th, st, so I built this utility function that uses the modulus % operator to check the divisor of each day number and apply the right suffix (aimed at an American audience but might be the same elsewhere?).
/**
* setDateSuffix()
*
* Desc: Takes two digit date, adds 'st', 'nd', 'rd', etc
*
* #param { integer } num - a number date
*/
export const setDateSuffix = (num) => {
const j = num % 10,
k = num % 100
if (j === 1 && k !== 11) {
return num + "st";
}
if (j === 2 && k !== 12) {
return num + "nd";
}
if (j === 3 && k !== 13) {
return num + "rd";
}
return num + "th";
}
Altogether now.. Long winded way of getting here, but if I am given an ISO or Unix date and I want Month DDth, YYYY, this is what I run:
// setDateSuffix IS NOT PART OF BUILT-IN JS!
const newDate = new Date('23-12-2010')
const simpleDate = `${newDate.toLocaleString('en-us', { month: 'long' } )} ${setDateSuffix(newDate.getDate())}, ${newDate.getFullYear()}`
// yields: December 23rd, 2010
Note - all of this will likely change, hopefully for the better, when temporal becomes a reality in JS: https://github.com/tc39/proposal-temporal. Look forward to somebody's 2030 update of this post!

Categories

Resources