Format JavaScript Date to yyyy-mm-dd

2019-01-01 02:12发布

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

27条回答
刘海飞了
2楼-- · 2019-01-01 02:16

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

查看更多
心情的温度
3楼-- · 2019-01-01 02:19

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/

查看更多
听够珍惜
4楼-- · 2019-01-01 02:20
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
查看更多
伤终究还是伤i
5楼-- · 2019-01-01 02:20

Date.js is great for this.

require("datejs")
(new Date()).toString("yyyy-MM-dd")
查看更多
旧时光的记忆
6楼-- · 2019-01-01 02:20

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>
查看更多
浮光初槿花落
7楼-- · 2019-01-01 02:21

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);
查看更多
登录 后发表回答