[javascript] Format JavaScript date as yyyy-mm-dd

I have a date with the format Sun May 11,2014. How can I convert it to 2014-05-11 using JavaScript?

_x000D_
_x000D_
function taskDate(dateMilli) {_x000D_
    var d = (new Date(dateMilli) + '').split(' ');_x000D_
    d[2] = d[2] + ',';_x000D_
_x000D_
    return [d[0], d[1], d[2], d[3]].join(' ');_x000D_
}_x000D_
_x000D_
var datemilli = Date.parse('Sun May 11,2014');_x000D_
console.log(taskDate(datemilli));
_x000D_
_x000D_
_x000D_

The code above gives me the same date format, sun may 11,2014. How can I fix this?

This question is related to javascript date formatting date-format

The answer is


If you use momentjs, now they include a constant for that format YYYY-MM-DD:

date.format(moment.HTML5_FMT.DATE)

2020 ANSWER

You can use the native .toLocaleDateString() function which supports several useful params like locale (to select a format like MM/DD/YYYY or YYYY/MM/DD), timezone (to convert the date) and formats details options (eg: 1 vs 01 vs January).

Examples

new Date().toLocaleDateString() // 8/19/2020

new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 08/19/2020 (month and day with two digits)

new Date().toLocaleDateString('en-ZA'); // 2020/08/19 (year/month/day) notice the different locale

new Date().toLocaleDateString('en-CA'); // 2020-08-19 (year-month-day) notice the different locale

new Date().toLocaleString("en-US", {timeZone: "America/New_York"}); // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)

new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"});  // 09 (just the hour)

Notice that sometimes to output a date in your specific desire format, you have to find a compatible locale with that format. You can find the locale examples here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all

Please notice that locale just change the format, if you want to transform a specific date to a specific country or city time equivalent then you need to use the timezone param.


Retrieve year, month, and day, and then put them together. Straight, simple, and accurate.

_x000D_
_x000D_
function formatDate(date) {_x000D_
    var year = date.getFullYear().toString();_x000D_
    var month = (date.getMonth() + 101).toString().substring(1);_x000D_
    var day = (date.getDate() + 100).toString().substring(1);_x000D_
    return year + "-" + month + "-" + day;_x000D_
}_x000D_
_x000D_
//Usage example:_x000D_
alert(formatDate(new Date()));
_x000D_
_x000D_
_x000D_


format = function date2str(x, y) {
    var z = {
        M: x.getMonth() + 1,
        d: x.getDate(),
        h: x.getHours(),
        m: x.getMinutes(),
        s: x.getSeconds()
    };
    y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
        return ((v.length > 1 ? "0" : "") + z[v.slice(-1)]).slice(-2)
    });

    return y.replace(/(y+)/g, function(v) {
        return x.getFullYear().toString().slice(-v.length)
    });
}

Result:

format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11

If you don't have anything against using libraries, you could just use the Moments.js library like so:

_x000D_
_x000D_
var now = new Date();_x000D_
var dateString = moment(now).format('YYYY-MM-DD');_x000D_
_x000D_
var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:mm:ss');
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_


When ES2018 rolls around (works in chrome) you can simply regex it

(new Date())
    .toISOString()
    .replace(
        /^(?<year>\d+)-(?<month>\d+)-(?<day>\d+)T.*$/,
        '$<year>-$<month>-$<day>'
    )

2020-07-14

Or if you'd like something pretty versatile with no libraries whatsoever

(new Date())
    .toISOString()
    .match(
        /^(?<yyyy>\d\d(?<yy>\d\d))-(?<mm>0?(?<m>\d+))-(?<dd>0?(?<d>\d+))T(?<HH>0?(?<H>\d+)):(?<MM>0?(?<M>\d+)):(?<SSS>(?<SS>0?(?<S>\d+))\.\d+)(?<timezone>[A-Z][\dA-Z.-:]*)$/
    )
    .groups

Which results in extracting the following

{
    H: "8"
    HH: "08"
    M: "45"
    MM: "45"
    S: "42"
    SS: "42"
    SSS: "42.855"
    d: "14"
    dd: "14"
    m: "7"
    mm: "07"
    timezone: "Z"
    yy: "20"
    yyyy: "2020"
}

Which you can use like so with replace(..., '$<d>/$<m>/\'$<yy> @ $<H>:$<MM>') as at the top instead of .match(...).groups to get

14/7/'20 @ 8:45

new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );

or

new Date().toISOString().split('T')[0]
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString()
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString().split('T')[0]

Try this!


_x000D_
_x000D_
const today = new Date(); // or whatever _x000D_
_x000D_
const yearFirstFormater = (date): string => {_x000D_
    const modifiedDate = new Date(date).toISOString().slice(0, 10);_x000D_
    return `${modifiedDate.split('-')[0]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}`;_x000D_
}_x000D_
_x000D_
const monthFirstFormater = (date): string => {_x000D_
    const modifiedDate = new Date(date).toISOString().slice(0, 10);_x000D_
    return `${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[0]}`;_x000D_
}_x000D_
_x000D_
const dayFirstFormater = (date): string => {_x000D_
    const modifiedDate = new Date(date).toISOString().slice(0, 10);_x000D_
    return `${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[0]}`;_x000D_
}_x000D_
_x000D_
console.log(yearFirstFormater(today));_x000D_
console.log(monthFirstFormater(today));_x000D_
console.log(dayFirstFormater(today));
_x000D_
_x000D_
_x000D_


const formatDate = d => [
    d.getFullYear(),
    (d.getMonth() + 1).toString().padStart(2, '0'),
    d.getDate().toString().padStart(2, '0')
].join('-');

You can make use of padstart.

padStart(n, '0') ensures that a minimum of n characters are in a string and prepends it with '0's until that length is reached.

join('-') concatenates an array, adding '-' symbol between every elements.

getMonth() starts at 0 hence the +1.


The simplest way to convert your date to the yyyy-mm-dd format, is to do this:

var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
                    .toISOString()
                    .split("T")[0];

How it works:

  • new Date("Sun May 11,2014") converts the string "Sun May 11,2014" to a date object that represents the time Sun May 11 2014 00:00:00 in a timezone based on current locale (host system settings)
  • new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )) converts your date to a date object that corresponds with the time Sun May 11 2014 00:00:00 in UTC (standard time) by subtracting the time zone offset
  • .toISOString() converts the date object to an ISO 8601 string 2014-05-11T00:00:00.000Z
  • .split("T") splits the string to array ["2014-05-11", "00:00:00.000Z"]
  • [0] takes the first element of that array

Demo

_x000D_
_x000D_
var date = new Date("Sun May 11,2014");_x000D_
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))_x000D_
                    .toISOString()_x000D_
                    .split("T")[0];_x000D_
_x000D_
console.log(dateString);
_x000D_
_x000D_
_x000D_


formatDate(date) {
  const d = new Date(date)
  const ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
  const mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d);
  const da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
  return `${da}-${mo}-${ye}`;
}

console.log("Formatated Date : ", formatDate("09/25/2020") )
// Output :: Formatated Date : 25-Sep-2020

This code change the order of DD MM YYYY

function convertDate(format, date) {
    let formatArray = format.split('/');
    if (formatArray.length != 3) {
        console.error('Use a valid Date format');
        return;
    }
    function getType(type) { return type == 'DD' ? d.getDate() : type == 'MM' ? d.getMonth() + 1 : type == 'YYYY' && d.getFullYear(); }
    function pad(s) { return (s < 10) ? '0' + s : s; }
    var d = new Date(date);
    return [pad(getType(formatArray[0])), pad(getType(formatArray[1])), getType(formatArray[2])].join('/');
}

All given answers are great and helped me big. In my situation, I wanted to get the current date in yyyy mm dd format along with date-1. Here is what worked for me.

var endDate = new Date().toISOString().slice(0, 10); // To get the Current Date in YYYY MM DD Format

var newstartDate = new Date();
newstartDate.setDate(newstartDate.getDate() - 1);
var startDate = newstartDate.toISOString().slice(0, 10); // To get the Yesterday's Date in YYYY MM DD Format
alert(startDate);

You can try this: https://www.npmjs.com/package/timesolver

npm i timesolver

Use it in your code:

const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, "YYYY-MM-DD");

You can get the date string by using this method:

getString

new Date(new Date(YOUR_DATE.toISOString()).getTime() - 
                 (YOUR_DATE.getTimezoneOffset() * 60 * 1000)).toISOString().substr(0, 10)

This worked for me, and you can paste this directly into your HTML if needed for testing:

<script type="text/javascript">
    if (datefield.type!="date"){ // If the browser doesn't support input type="date",
                                 // initialize date picker widget:
        jQuery(function($){ // On document.ready
            $('#Date').datepicker({
                dateFormat: 'yy-mm-dd', // THIS IS THE IMPORTANT PART!!!
                showOtherMonths: true,
                selectOtherMonths: true,
                changeMonth: true,
                minDate: '2016-10-19',
                maxDate: '2016-11-03'
            });
        })
    }
</script>

Shortest

.toJSON().slice(0,10);

_x000D_
_x000D_
var d = new Date('Sun May 11,2014' +' UTC');   // Parse as UTC
let str = d.toJSON().slice(0,10);              // Show as UTC

console.log(str);
_x000D_
_x000D_
_x000D_


I modified Samit Satpute's response as follows:

_x000D_
_x000D_
var newstartDate = new Date();_x000D_
// newstartDate.setDate(newstartDate.getDate() - 1);_x000D_
var startDate = newstartDate.toISOString().replace(/[-T:\.Z]/g, ""); //.slice(0, 10); // To get the Yesterday's Date in YYYY MM DD Format_x000D_
console.log(startDate);
_x000D_
_x000D_
_x000D_


It is easily accomplished by my date-shortcode package:

const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYY-MM-DD}', 'Sun May 11,2014')
//=> '2014-05-11'

I suggest using something like formatDate-js instead of trying to replicate it every time. Just use a library that supports all the major strftime actions.

new Date().format("%Y-%m-%d")

If the date needs to be the same across all time zones, for example represents some value from the database, then be sure to use UTC versions of the day, month, fullyear functions on the JavaScript date object as this will display in UTC time and avoid off-by-one errors in certain time zones.

Even better, use the Moment.js date library for this sort of formatting.


Just leverage the built-in toISOString method that brings your date to the ISO 8601 format:

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]

This worked for me to get the current date in the desired format (YYYYMMDD HH:MM:SS):

var d = new Date();

var date1 = d.getFullYear() + '' +
            ((d.getMonth()+1) < 10 ? "0" + (d.getMonth() + 1) : (d.getMonth() + 1)) +
            '' +
            (d.getDate() < 10 ? "0" + d.getDate() : d.getDate());

var time1 = (d.getHours() < 10 ? "0" + d.getHours() : d.getHours()) +
            ':' +
            (d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes()) +
            ':' +
            (d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds());

print(date1+' '+time1);

A few of the previous answer were OK, but they weren't very flexible. I wanted something that could really handle more edge cases, so I took @orangleliu 's answer and expanded on it. https://jsfiddle.net/8904cmLd/1/

function DateToString(inDate, formatString) {
    // Written by m1m1k 2018-04-05

    // Validate that we're working with a date
    if(!isValidDate(inDate))
    {
        inDate = new Date(inDate);
    }

    // See the jsFiddle for extra code to be able to use DateToString('Sun May 11,2014', 'USA');
    //formatString = CountryCodeToDateFormat(formatString);

    var dateObject = {
        M: inDate.getMonth() + 1,
        d: inDate.getDate(),
        D: inDate.getDate(),
        h: inDate.getHours(),
        m: inDate.getMinutes(),
        s: inDate.getSeconds(),
        y: inDate.getFullYear(),
        Y: inDate.getFullYear()
    };

    // Build Regex Dynamically based on the list above.
    // It should end up with something like this: "/([Yy]+|M+|[Dd]+|h+|m+|s+)/g"
    var dateMatchRegex = joinObj(dateObject, "+|") + "+";
    var regEx = new RegExp(dateMatchRegex,"g");
    formatString = formatString.replace(regEx, function(formatToken) {
        var datePartValue = dateObject[formatToken.slice(-1)];
        var tokenLength = formatToken.length;

        // A conflict exists between specifying 'd' for no zero pad -> expand
        // to '10' and specifying yy for just two year digits '01' instead
        // of '2001'.  One expands, the other contracts.
        //
        // So Constrict Years but Expand All Else
        if (formatToken.indexOf('y') < 0 && formatToken.indexOf('Y') < 0)
        {
            // Expand single digit format token 'd' to
            // multi digit value '10' when needed
            var tokenLength = Math.max(formatToken.length, datePartValue.toString().length);
        }
        var zeroPad = (datePartValue.toString().length < formatToken.length ? "0".repeat(tokenLength) : "");
        return (zeroPad + datePartValue).slice(-tokenLength);
    });

    return formatString;
}

Example usage:

DateToString('Sun May 11,2014', 'MM/DD/yy');
DateToString('Sun May 11,2014', 'yyyy.MM.dd');
DateToString(new Date('Sun Dec 11,2014'),'yy-M-d');

No library is needed

Just pure JavaScript.

The example below gets the last two months from today:

_x000D_
_x000D_
var d = new Date()_x000D_
d.setMonth(d.getMonth() - 2);_x000D_
var dateString = new Date(d);_x000D_
console.log('Before Format', dateString, 'After format', dateString.toISOString().slice(0,10))
_x000D_
_x000D_
_x000D_


PHP compatible date format

Here is a small function which can take the same parameters as the PHP function date() and return a date/time string in JavaScript.

Note that not all date() format options from PHP are supported. You can extend the parts object to create the missing format-token

_x000D_
_x000D_
/**_x000D_
 * Date formatter with PHP "date()"-compatible format syntax._x000D_
 */_x000D_
const formatDate = (format, date) => {_x000D_
  if (!format) { format = 'Y-m-d' }_x000D_
  if (!date) { date = new Date() }_x000D_
_x000D_
  const parts = {_x000D_
    Y: date.getFullYear().toString(),_x000D_
    y: ('00' + (date.getYear() - 100)).toString().slice(-2),_x000D_
    m: ('0' + (date.getMonth() + 1)).toString().slice(-2),_x000D_
    n: (date.getMonth() + 1).toString(),_x000D_
    d: ('0' + date.getDate()).toString().slice(-2),_x000D_
    j: date.getDate().toString(),_x000D_
    H: ('0' + date.getHours()).toString().slice(-2),_x000D_
    G: date.getHours().toString(),_x000D_
    i: ('0' + date.getMinutes()).toString().slice(-2),_x000D_
    s: ('0' + date.getSeconds()).toString().slice(-2)_x000D_
  }_x000D_
_x000D_
  const modifiers = Object.keys(parts).join('')_x000D_
  const reDate = new RegExp('(?<!\\\\)[' + modifiers + ']', 'g')_x000D_
  const reEscape = new RegExp('\\\\([' + modifiers + '])', 'g')_x000D_
_x000D_
  return format_x000D_
    .replace(reDate, $0 => parts[$0])_x000D_
    .replace(reEscape, ($0, $1) => $1)_x000D_
}_x000D_
_x000D_
// ----- EXAMPLES -----_x000D_
console.log( formatDate() ); // "2019-05-21"_x000D_
console.log( formatDate('H:i:s') ); // "16:21:32"_x000D_
console.log( formatDate('Y-m-d, o\\n H:i:s') ); // "2019-05-21, on 16:21:32"_x000D_
console.log( formatDate('Y-m-d', new Date(2000000000000)) ); // "2033-05-18"
_x000D_
_x000D_
_x000D_

Gist

Here is a gist with an updated version of the formatDate() function and additional examples: https://gist.github.com/stracker-phil/c7b68ea0b1d5bbb97af0a6a3dc66e0d9


A combination of some of the answers:

var d = new Date(date);
date = [
  d.getFullYear(),
  ('0' + (d.getMonth() + 1)).slice(-2),
  ('0' + d.getDate()).slice(-2)
].join('-');

Simply use this:

var date = new Date('1970-01-01'); // Or your date here
console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' +  date.getFullYear());

Simple and sweet ;)


toISOString() assumes your date is local time and converts it to UTC. You will get an incorrect date string.

The following method should return what you need.

Date.prototype.yyyymmdd = function() {         

    var yyyy = this.getFullYear().toString();                                    
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
    var dd  = this.getDate().toString();             

    return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

Source: https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/


We run constantly into problems like this. Every solution looks so individual. But looking at php, we have a way dealing with different formats. And there is a port of php's strtotime function at https://locutus.io/php/datetime/strtotime/. A small open source npm package from me as an alternative way:

<script type="module">
import { datebob } from "@dipser/datebob.js";
console.log( datebob('Sun May 11, 2014').format('Y-m-d') ); 
</script>

See datebob.js


I use this way to get the date in format yyyy-mm-dd :)

var todayDate = new Date().toISOString().slice(0,10);

To consider the timezone also, this one-liner should be good without any library:

new Date().toLocaleString("en-IN", {timeZone: "Asia/Kolkata"}).split(',')[0]

You can use toLocaleDateString('fr-CA') on Date object

_x000D_
_x000D_
console.log(new Date('Sun May 11,2014').toLocaleDateString('fr-CA'));
_x000D_
_x000D_
_x000D_

Also I found out that those locales give right result from this locales list List of All Locales and Their Short Codes?

'en-CA'
'fr-CA'
'lt-LT'
'sv-FI'
'sv-SE'

_x000D_
_x000D_
var localesList = ["af-ZA",_x000D_
  "am-ET",_x000D_
  "ar-AE",_x000D_
  "ar-BH",_x000D_
  "ar-DZ",_x000D_
  "ar-EG",_x000D_
  "ar-IQ",_x000D_
  "ar-JO",_x000D_
  "ar-KW",_x000D_
  "ar-LB",_x000D_
  "ar-LY",_x000D_
  "ar-MA",_x000D_
  "arn-CL",_x000D_
  "ar-OM",_x000D_
  "ar-QA",_x000D_
  "ar-SA",_x000D_
  "ar-SY",_x000D_
  "ar-TN",_x000D_
  "ar-YE",_x000D_
  "as-IN",_x000D_
  "az-Cyrl-AZ",_x000D_
  "az-Latn-AZ",_x000D_
  "ba-RU",_x000D_
  "be-BY",_x000D_
  "bg-BG",_x000D_
  "bn-BD",_x000D_
  "bn-IN",_x000D_
  "bo-CN",_x000D_
  "br-FR",_x000D_
  "bs-Cyrl-BA",_x000D_
  "bs-Latn-BA",_x000D_
  "ca-ES",_x000D_
  "co-FR",_x000D_
  "cs-CZ",_x000D_
  "cy-GB",_x000D_
  "da-DK",_x000D_
  "de-AT",_x000D_
  "de-CH",_x000D_
  "de-DE",_x000D_
  "de-LI",_x000D_
  "de-LU",_x000D_
  "dsb-DE",_x000D_
  "dv-MV",_x000D_
  "el-GR",_x000D_
  "en-029",_x000D_
  "en-AU",_x000D_
  "en-BZ",_x000D_
  "en-CA",_x000D_
  "en-GB",_x000D_
  "en-IE",_x000D_
  "en-IN",_x000D_
  "en-JM",_x000D_
  "en-MY",_x000D_
  "en-NZ",_x000D_
  "en-PH",_x000D_
  "en-SG",_x000D_
  "en-TT",_x000D_
  "en-US",_x000D_
  "en-ZA",_x000D_
  "en-ZW",_x000D_
  "es-AR",_x000D_
  "es-BO",_x000D_
  "es-CL",_x000D_
  "es-CO",_x000D_
  "es-CR",_x000D_
  "es-DO",_x000D_
  "es-EC",_x000D_
  "es-ES",_x000D_
  "es-GT",_x000D_
  "es-HN",_x000D_
  "es-MX",_x000D_
  "es-NI",_x000D_
  "es-PA",_x000D_
  "es-PE",_x000D_
  "es-PR",_x000D_
  "es-PY",_x000D_
  "es-SV",_x000D_
  "es-US",_x000D_
  "es-UY",_x000D_
  "es-VE",_x000D_
  "et-EE",_x000D_
  "eu-ES",_x000D_
  "fa-IR",_x000D_
  "fi-FI",_x000D_
  "fil-PH",_x000D_
  "fo-FO",_x000D_
  "fr-BE",_x000D_
  "fr-CA",_x000D_
  "fr-CH",_x000D_
  "fr-FR",_x000D_
  "fr-LU",_x000D_
  "fr-MC",_x000D_
  "fy-NL",_x000D_
  "ga-IE",_x000D_
  "gd-GB",_x000D_
  "gl-ES",_x000D_
  "gsw-FR",_x000D_
  "gu-IN",_x000D_
  "ha-Latn-NG",_x000D_
  "he-IL",_x000D_
  "hi-IN",_x000D_
  "hr-BA",_x000D_
  "hr-HR",_x000D_
  "hsb-DE",_x000D_
  "hu-HU",_x000D_
  "hy-AM",_x000D_
  "id-ID",_x000D_
  "ig-NG",_x000D_
  "ii-CN",_x000D_
  "is-IS",_x000D_
  "it-CH",_x000D_
  "it-IT",_x000D_
  "iu-Cans-CA",_x000D_
  "iu-Latn-CA",_x000D_
  "ja-JP",_x000D_
  "ka-GE",_x000D_
  "kk-KZ",_x000D_
  "kl-GL",_x000D_
  "km-KH",_x000D_
  "kn-IN",_x000D_
  "kok-IN",_x000D_
  "ko-KR",_x000D_
  "ky-KG",_x000D_
  "lb-LU",_x000D_
  "lo-LA",_x000D_
  "lt-LT",_x000D_
  "lv-LV",_x000D_
  "mi-NZ",_x000D_
  "mk-MK",_x000D_
  "ml-IN",_x000D_
  "mn-MN",_x000D_
  "mn-Mong-CN",_x000D_
  "moh-CA",_x000D_
  "mr-IN",_x000D_
  "ms-BN",_x000D_
  "ms-MY",_x000D_
  "mt-MT",_x000D_
  "nb-NO",_x000D_
  "ne-NP",_x000D_
  "nl-BE",_x000D_
  "nl-NL",_x000D_
  "nn-NO",_x000D_
  "nso-ZA",_x000D_
  "oc-FR",_x000D_
  "or-IN",_x000D_
  "pa-IN",_x000D_
  "pl-PL",_x000D_
  "prs-AF",_x000D_
  "ps-AF",_x000D_
  "pt-BR",_x000D_
  "pt-PT",_x000D_
  "qut-GT",_x000D_
  "quz-BO",_x000D_
  "quz-EC",_x000D_
  "quz-PE",_x000D_
  "rm-CH",_x000D_
  "ro-RO",_x000D_
  "ru-RU",_x000D_
  "rw-RW",_x000D_
  "sah-RU",_x000D_
  "sa-IN",_x000D_
  "se-FI",_x000D_
  "se-NO",_x000D_
  "se-SE",_x000D_
  "si-LK",_x000D_
  "sk-SK",_x000D_
  "sl-SI",_x000D_
  "sma-NO",_x000D_
  "sma-SE",_x000D_
  "smj-NO",_x000D_
  "smj-SE",_x000D_
  "smn-FI",_x000D_
  "sms-FI",_x000D_
  "sq-AL",_x000D_
  "sr-Cyrl-BA",_x000D_
  "sr-Cyrl-CS",_x000D_
  "sr-Cyrl-ME",_x000D_
  "sr-Cyrl-RS",_x000D_
  "sr-Latn-BA",_x000D_
  "sr-Latn-CS",_x000D_
  "sr-Latn-ME",_x000D_
  "sr-Latn-RS",_x000D_
  "sv-FI",_x000D_
  "sv-SE",_x000D_
  "sw-KE",_x000D_
  "syr-SY",_x000D_
  "ta-IN",_x000D_
  "te-IN",_x000D_
  "tg-Cyrl-TJ",_x000D_
  "th-TH",_x000D_
  "tk-TM",_x000D_
  "tn-ZA",_x000D_
  "tr-TR",_x000D_
  "tt-RU",_x000D_
  "tzm-Latn-DZ",_x000D_
  "ug-CN",_x000D_
  "uk-UA",_x000D_
  "ur-PK",_x000D_
  "uz-Cyrl-UZ",_x000D_
  "uz-Latn-UZ",_x000D_
  "vi-VN",_x000D_
  "wo-SN",_x000D_
  "xh-ZA",_x000D_
  "yo-NG",_x000D_
  "zh-CN",_x000D_
  "zh-HK",_x000D_
  "zh-MO",_x000D_
  "zh-SG",_x000D_
  "zh-TW",_x000D_
  "zu-ZA"_x000D_
];_x000D_
_x000D_
localesList.forEach(lcl => {_x000D_
  if ("2014-05-11" === new Date('Sun May 11,2014').toLocaleDateString(lcl)) {_x000D_
    console.log(lcl, new Date('Sun May 11,2014').toLocaleDateString(lcl));_x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_


_x000D_
_x000D_
function myYmd(D){_x000D_
    var pad = function(num) {_x000D_
        var s = '0' + num;_x000D_
        return s.substr(s.length - 2);_x000D_
    }_x000D_
    var Result = D.getFullYear() + '-' + pad((D.getMonth() + 1)) + '-' + pad(D.getDate());_x000D_
    return Result;_x000D_
}_x000D_
_x000D_
var datemilli = new Date('Sun May 11,2014');_x000D_
document.write(myYmd(datemilli));
_x000D_
_x000D_
_x000D_


Yet another combination of the answers. Nicely readable, but a little lengthy.

function getCurrentDayTimestamp() {
  const d = new Date();

  return new Date(
    Date.UTC(
      d.getFullYear(),
      d.getMonth(),
      d.getDate(),
      d.getHours(),
      d.getMinutes(),
      d.getSeconds()
    )
  // `toIsoString` returns something like "2017-08-22T08:32:32.847Z"
  // and we want the first part ("2017-08-22")
  ).toISOString().slice(0, 10);
}

Reformatting a date string is fairly straightforward, e.g.

_x000D_
_x000D_
var s = 'Sun May 11,2014';_x000D_
_x000D_
function reformatDate(s) {_x000D_
  function z(n){return ('0' + n).slice(-2)}_x000D_
  var months = [,'jan','feb','mar','apr','may','jun',_x000D_
                 'jul','aug','sep','oct','nov','dec'];_x000D_
  var b = s.split(/\W+/);_x000D_
  return b[3] + '-' +_x000D_
    z(months.indexOf(b[1].substr(0,3).toLowerCase())) + '-' +_x000D_
    z(b[2]);_x000D_
}_x000D_
_x000D_
console.log(reformatDate(s));
_x000D_
_x000D_
_x000D_


None of these answers quite satisfied me. I wanted a cross-platform solution that gave me the day in the local timezone without using any external libraries.

This is what I came up with:

function localDay(time) {
  var minutesOffset = time.getTimezoneOffset()
  var millisecondsOffset = minutesOffset*60*1000
  var local = new Date(time - millisecondsOffset)
  return local.toISOString().substr(0, 10)
}

That should return the day of the date, in YYYY-MM-DD format, in the timezone the date references.

So for example, localDay(new Date("2017-08-24T03:29:22.099Z")) will return "2017-08-23" even though it's already the 24th at UTC.

You'll need to polyfill Date.prototype.toISOString for it to work in Internet Explorer 8, but it should be supported everywhere else.


Date.js is great for this.

require("datejs")
(new Date()).toString("yyyy-MM-dd")

_x000D_
_x000D_
var d = new Date("Sun May 1,2014");_x000D_
_x000D_
var year  = d.getFullYear();_x000D_
var month = d.getMonth() + 1;_x000D_
var day   = d.getDate(); _x000D_
_x000D_
month = checkZero(month);             _x000D_
day   = checkZero(day);_x000D_
_x000D_
var date = "";_x000D_
_x000D_
date += year;_x000D_
date += "-";_x000D_
date += month;_x000D_
date += "-";_x000D_
date += day;_x000D_
_x000D_
document.querySelector("#display").innerHTML = date;_x000D_
    _x000D_
function checkZero(i) _x000D_
{_x000D_
    if (i < 10) _x000D_
    {_x000D_
        i = "0" + i_x000D_
    };  // add zero in front of numbers < 10_x000D_
_x000D_
    return i;_x000D_
}
_x000D_
<div id="display"></div>
_x000D_
_x000D_
_x000D_


Here is one way to do it:

var date = Date.parse('Sun May 11,2014');

function format(date) {
  date = new Date(date);

  var day = ('0' + date.getDate()).slice(-2);
  var month = ('0' + (date.getMonth() + 1)).slice(-2);
  var year = date.getFullYear();

  return year + '-' + month + '-' + day;
}

console.log(format(date));

Format and finding maximum and minimum date from hashmap data:

_x000D_
_x000D_
var obj = {"a":'2001-15-01', "b": '2001-12-02' , "c": '2001-1-03'};_x000D_
_x000D_
function findMaxMinDate(obj){_x000D_
  let formatEncode = (id)=> { let s = id.split('-'); return `${s[0]+'-'+s[2]+'-'+s[1]}`}_x000D_
  let formatDecode = (id)=> { let s = id.split('/'); return `${s[2]+'-'+s[0]+'-'+s[1]}`}_x000D_
  let arr = Object.keys( obj ).map(( key )=> { return new Date(formatEncode(obj[key])); });_x000D_
  let min = new Date(Math.min.apply(null, arr)).toLocaleDateString();_x000D_
  let max = new Date(Math.max.apply(null, arr)).toLocaleDateString();_x000D_
  return {maxd: `${formatDecode(max)}`, mind:`${formatDecode(min)}`}_x000D_
}_x000D_
_x000D_
console.log(findMaxMinDate(obj));
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to formatting

How to add empty spaces into MD markdown readme on GitHub? VBA: Convert Text to Number How to change indentation in Visual Studio Code? How do you change the formatting options in Visual Studio Code? (Excel) Conditional Formatting based on Adjacent Cell Value 80-characters / right margin line in Sublime Text 3 Format certain floating dataframe columns into percentage in pandas Format JavaScript date as yyyy-mm-dd AngularJS format JSON string output converting multiple columns from character to numeric format in r

Examples related to date-format

Format JavaScript date as yyyy-mm-dd How to format date in angularjs Rails formatting date How to change date format using jQuery? How to format Joda-Time DateTime to only mm/dd/yyyy? Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST Display current time in 12 hour format with AM/PM java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2 Converting a string to a date in a cell