Format JavaScript Date to yyyy-mm-dd

2019-01-01 02:27发布

问题:

Hi all i have a Date format Sun May 11,2014 how can i convert it to 2014-05-11 in javascript.

function taskDate(dateMilli) {
    var d = (new Date(dateMilli) + \'\').split(\' \');
    d[2] = d[2] + \',\';

    return [d[0], d[1], d[2], d[3]].join(\' \');
}
var datemilli = Date.parse(\'Sun May 11,2014\');
taskdate(datemilli);

the above code gives me same date format sun may 11,2014 please help

回答1:

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(\'-\');
}

usage example:

alert(formatDate(\'Sun May 11,2014\'));

Output:

2014-05-11

Demo on fiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/



回答2:

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

yourDate.toISOString().split(\'T\')[0]

where yourDate is your date object.



回答3:

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

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


回答4:

The simplest way to convert your date to 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 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

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

console.log(dateString);



回答5:

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\" : \"\") + eval(\'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


回答6:

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(\'-\');


回答7:

toISOString() assumes your date is local time and converts it to UTC. You will get 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/



回答8:

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



回答9:

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 date string by using this method:

getString

Hope this will help you!



回答10:

I suggest using something like this https://github.com/brightbits/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\")


回答11:

None of these answers quite satisfied me. I wanted a cross platform solution that gives 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 IE8, but it should be supported everywhere else.



回答12:

If you don\'t have anything against using libraries; you could just use moments.js library like so...

var now = new Date();
var dateString = moment(now).format(\'YYYY-MM-DD\');

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



回答13:

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

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



回答14:

function myYmd(D){
    var pad = function(num) {
        var s = \'0\' + num;
        return s.substr(s.length - 2);
    }
    var Result = D.getFullYear() + \'-\' + pad((D.getMonth() + 1)) + \'-\' + pad(D.getDate());
    return Result;
}

var datemilli = new Date(\'Sun May 11,2014\');
document.write(myYmd(datemilli));



回答15:

Reformatting a date string is fairly straight forward, e.g.

var s = \'Sun May 11,2014\';

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

console.log(reformatDate(s));



回答16:

Date.js is great for this.

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


回答17:

function formatDate(date) {
    var year = date.getFullYear().toString();
    var month = (date.getMonth() + 101).toString().substring(1);
    var day = (date.getDate() + 100).toString().substring(1);
    return year + \"-\" + month + \"-\" + day;
}

alert(formatDate(new Date()));



回答18:

This worked for me to get the current date in 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);


回答19:

If the date needs to be same across all timezones for example represents some value from database then be sure to use utc versions of the day, month, fullyear functions on js date object as this will display in utc time and avoid off by 1 errors in certain time zones. Even better use moment.js date library for this sort of formatting



回答20:

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


回答21:

I modified Samit Satpute\'s response as follows:

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



回答22:

Easily accomplished by my date-shortcode package:

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


回答23:

A few of these above were ok - but 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.
  // 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\');


回答24:

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


回答25:

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


回答26:

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


回答27:

Just Use Like this Definatly Working for YYYY MM DD like as (2017-03-12)

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