If you're using Node.js, you're sure to have EcmaScript 5, and so Date has a toISOString method. You're asking for a slight modification of ISO8601:
new Date().toISOString()
> '2012-11-04T14:51:06.157Z'
So just cut a few things out, and you're set:
new Date().toISOString().
replace(/T/, ' '). // replace T with a space
replace(/\..+/, '') // delete the dot and everything after
> '2012-11-04 14:55:45'
Or, in one line: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
ISO8601 is necessarily UTC (also indicated by the trailing Z on the first result), so you get UTC by default (always a good thing).
Answer from chbrown on Stack OverflowVideos
If you're using Node.js, you're sure to have EcmaScript 5, and so Date has a toISOString method. You're asking for a slight modification of ISO8601:
new Date().toISOString()
> '2012-11-04T14:51:06.157Z'
So just cut a few things out, and you're set:
new Date().toISOString().
replace(/T/, ' '). // replace T with a space
replace(/\..+/, '') // delete the dot and everything after
> '2012-11-04 14:55:45'
Or, in one line: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
ISO8601 is necessarily UTC (also indicated by the trailing Z on the first result), so you get UTC by default (always a good thing).
UPDATE 2021-10-06: Added Day.js and remove spurious edit by @ashleedawg
UPDATE 2021-04-07: Luxon added by @Tampa.
UPDATE 2021-02-28: It should now be noted that Moment.js is no longer being actively developed. It won't disappear in a hurry because it is embedded in so many other things. The website has some recommendations for alternatives and an explanation of why.
UPDATE 2017-03-29: Added date-fns, some notes on Moment and Datejs
UPDATE 2016-09-14: Added SugarJS which seems to have some excellent date/time functions.
OK, since no one has actually provided an actual answer, here is mine.
A library is certainly the best bet for handling dates and times in a standard way. There are lots of edge cases in date/time calculations so it is useful to be able to hand-off the development to a library.
Here is a list of the main Node compatible time formatting libraries:
- Day.js [added 2021-10-06] "Fast 2kB alternative to Moment.js with the same modern API"
- Luxon [added 2017-03-29, thanks to Tampa] "A powerful, modern, and friendly wrapper for JavaScript dates and times." - MomentJS rebuilt from the ground up with immutable types, chaining and much more.
- Moment.js [thanks to Mustafa] "A lightweight (4.3k) javascript date library for parsing, manipulating, and formatting dates" - Includes internationalization, calculations and relative date formats - Update 2017-03-29: Not quite so light-weight any more but still the most comprehensive solution, especially if you need timezone support. - Update 2021-02-28: No longer in active development.
- date-fns [added 2017-03-29, thanks to Fractalf] Small, fast, works with standard JS date objects. Great alternative to Moment if you don't need timezone support.
- SugarJS - A general helper library adding much needed features to JavaScripts built-in object types. Includes some excellent looking date/time capabilities.
- strftime - Just what it says, nice and simple
- dateutil - This is the one I used to use before MomentJS
- node-formatdate
- TimeTraveller - "Time Traveller provides a set of utility methods to deal with dates. From adding and subtracting, to formatting. Time Traveller only extends date objects that it creates, without polluting the global namespace."
- Tempus [thanks to Dan D] - UPDATE: this can also be used with Node and deployed with npm, see the docs
There are also non-Node libraries:
- Datejs [thanks to Peter Olson] - not packaged in npm or GitHub so not quite so easy to use with Node - not really recommended as not updated since 2007!
[Addendum 12/2022]: Here's a library to format dates using Intl.DateTimeFormat.
[Addendum 01/2024]: And here is a (ES-)Date manipulation library
Try something like this
var d = new Date,
dformat = [d.getMonth()+1,
d.getDate(),
d.getFullYear()].join('/')+' '+
[d.getHours(),
d.getMinutes(),
d.getSeconds()].join(':');
If you want leading zero's for values < 10, use this number extension
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3'
Applied to the previous code:
var d = new Date,
dformat = [(d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('/') +' ' +
[d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'
See this code in [jsfiddle][1]
[edit 2019] Using ES20xx, you can use a template literal and the new padStart string extension.
const dt = new Date();
const padL = (nr, len = 2, chr = `0`) => `${nr}`.padStart(2, chr);
console.log(`${
padL(dt.getMonth()+1)}/${
padL(dt.getDate())}/${
dt.getFullYear()} ${
padL(dt.getHours())}:${
padL(dt.getMinutes())}:${
padL(dt.getSeconds())}`
);
You can always format a date by extracting the parts and combine them using string functions in desired order:
function formatDate(date) {
let datePart = [
date.getMonth() + 1,
date.getDate(),
date.getFullYear()
].map((n, i) => n.toString().padStart(i === 2 ? 4 : 2, "0")).join("/");
let timePart = [
date.getHours(),
date.getMinutes(),
date.getSeconds()
].map((n, i) => n.toString().padStart(2, "0")).join(":");
return datePart + " " + timePart;
}
let date = new Date();
console.log("%o => %s", date, formatDate(date));
» npm install dateformat
Just leverage the built-in toISOString method that brings your date to the ISO 8601 format:
let yourDate = new Date()
yourDate.toISOString().split('T')[0]
Where yourDate is your date object.
Edit: @exbuddha wrote this to handle time zone in the comments:
const offset = yourDate.getTimezoneOffset()
yourDate = new Date(yourDate.getTime() - (offset*60*1000))
return yourDate.toISOString().split('T')[0]
You can do:
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
console.log(formatDate('Sun May 11,2014'));
Usage example:
console.log(formatDate('Sun May 11,2014'));
Output:
2014-05-11
Demo on JSFiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/
Dates in JavaScript are very annoying to deal with. So in this post, I will show you a basic of dates in JS to help you get started with this tedious API.
I've also made a video on this topic, so if a video is more to you're liking then you can check it out here.
1. Epoch
-
The epoch is a specific time that the JS date API started its timestamp count.
-
The date is 1970-01-01.
2. The date class
-
The date class in JS is a used to create a new date object which has the value of the one passed as the constructor.
new Date("2016-02-12");
-
In case you don't provide a date the new object will have the value of the current date.
3. The date format
-
The most used and default format for displaying dates is the
YYYY-MM-DDTHH:mm:ss.sssZformat.YYYY: Year MM: Month DD: Date T: Separator of the date from the time HH: Hour mm: Minute ss: Second sss: Millisecond Z: time zone
4. Date methods
-
Date.parse(): This method is used to change the above format and any other string format of dates into a timestamp that starts it's count from the epoch. -
Date.now(): Returns the current date using a parsed timestamp format. -
Date.UTC(): Creates a date based on the UTC(Universal Time Coordinate) time zone.
5. Date creation
-
Regular date creation.
new Date();
-
Date creation with custom date.
new Date("2012-12-12");
-
Date creation with arguments following the
YYYY-MM-DDTHH:mm:ss.sssformat.new Date(1998, 12, 11, 9, 30, 30, 998);
6. Date formating
-
The default date follows the above
YYYY-MM-DDTHH:mm:ss.sssZformat. -
Using
Date.parse()you can convert any date into a timestamp format. -
You can also use dates as strings:
const date = new Date();
date.toDateString(); // Thu Sept 12 2024
date.toTimeString(); // 12:00:33
date.toLocalDateString(); // Uses the current user's time zone to display date.
date.toLocalTimeString(); // Uses the current user's time zone to display time.
date.toISOString(); // Uses the default date format.
7. Date components
-
Date.getFullYear(): Returns the year only. -
Date.getMonth(): Returns the month only with a zero based indexing format meaning January will be displayed as 0 and February as 1, etc. -
Date.getDate(): Returns the date only. -
Date.getHours(): Returns the hour only. -
Date.getMinutes(): Returns the minute only. -
Date.getSeconds(): Returns the hour only. -
Date.getMilliseconds(): Returns the milliseconds only.
Conclusion
This is not the only functionality that the JS date API has but it's good starting point for you to keep on learning. Dates in JS could be frustrating at times but they are a very powerful tool that every developer should have at least a basic knowledge of.
For a more detailed look at the date API in JS take a look at my video here.