javascript 从字符串格式化日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20966410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:43:17  来源:igfitidea点击:

Formatting a datetime from a string

javascriptjqueryhtml

提问by Saritha.S.R

I have date in this format in JavaScript:

我在 JavaScript 中有这种格式的日期:

Fri Jan 27 2012 08:01:00 GMT+0530 (India Standard Time)

Fri Jan 27 2012 08:01:00 GMT+0530 (India Standard Time)

I want to format the date to MM/dd/yyyy HH:mm:ss.

我想将日期格式化为MM/dd/yyyy HH:mm:ss.

回答by Edgar Villegas Alvarado

With this:

有了这个:

//Formats d to MM/dd/yyyy HH:mm:ss format
function formatDate(d){
  function addZero(n){
     return n < 10 ? '0' + n : '' + n;
  }

    return addZero(d.getMonth()+1)+"/"+ addZero(d.getDate()) + "/" + d.getFullYear() + " " + 
           addZero(d.getHours()) + ":" + addZero(d.getMinutes()) + ":" + addZero(d.getMinutes());
}

var str = 'Fri Jan 27 2012 08:01:00 GMT+0530 (India Standard Time)';
var date = new Date(Date.parse(str));
var formatted = formatDate(date);
alert(formatted);  //alerts "01/26/2012 22:31:31"

Cheers

干杯

回答by Igle

Just concatenate it as a string like this:

只需将其连接为这样的字符串:

var date = new Date();
var month = (date.getMonth()+1) > 9 ? (date.getMonth()+1) : "0" + (date.getMonth()+1);
var day = (date.getDate()+1) > 9 ? (date.getDate()+1) : "0" + (date.getDate()+1);
var hours = (date.getHours()) > 9 ? (date.getHours()) : "0" + (date.getHours());
var minutes = (date.getMinutes()) > 9 ? (date.getMinutes()) : "0" + (date.getMinutes());
var seconds = (date.getSeconds()) > 9 ? (date.getSeconds()) : "0" + (date.getSeconds());

var dateString = 
    month + "/" + 
    day + "/" + 
    date.getFullYear() + " " + 
    hours + ":" + 
    minutes + ":" + 
    seconds;

And always remember, javascript Date's months are zero-based

永远记住,javascript 日期的月份是从零开始的

the Method .toLocaleStringreturns a similar result but with month and day switched like this:

该方法.toLocaleString返回类似的结果,但月份和日期如下切换:

dd/mm/yyyy HH:mm:ss

Here is a Fiddle

这是一个小提琴

回答by rajesh kakawat

try something like this

尝试这样的事情

        var date = new Date();
        var month = date.getMonth()+ 1;
        var dateString =  month + "/" + date.getDate() + "/" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
        console.log(dateString);

回答by lokopi

Hereis a plugin for datetimeformat

是一个用于日期时间格式的插件

  $(document).ready(function () {
        console.log($.format.date("Fri Jan 27 2012 08:01:00 GMT+0530 (India Standard Time)", "MM/dd/yyyy HH:mm:ss"));
    });