Javascript或jQuery中的自定义日期格式? [重复]

问题描述 投票:-4回答:2

这个问题在这里已有答案:

我需要格式化我的日期,如“2016-04-19T03:35:17.02”。我如何格式化日期格式,如使用javascript或jQuery。

请帮我任何一个。

javascript jquery
2个回答
-1
投票

在javascript中你有一个Date对象。首先,您必须创建对象:

var d = new Date();

然后,您可以为所需的每个部分创建一个变量:

// Get the year
var year = d.getFullYear();

// Get the month +1 because normally returns 0-11
var month = d.getMonth()+1;

// Format month to add a 0 if 1-9
var fMonth = month < 9 ? '0' + month : month;

// Get day and format it to add a 0 if 1-9
var fDay =  d.getDate() < 9 ? '0' + d.getDate() : d.getDate();

// Combine it into a single string
var dateStr = year +'-'+ fMonth +'-'+ fDay +'T';

这应该会让你“2016-05-22T”。其余的你可以自己完成。您可以使用w3schools的可用日期方法列表:http://www.w3schools.com/jsref/jsref_obj_date.asp


-2
投票

您可以使用这些方法getFullYear(), getMonth(), getDate(), getHours(), getMinutes(), getSeconds(), getMilliseconds()或像Moment.js这样的库,您可以使用方法.format()及其参数。

© www.soinside.com 2019 - 2024. All rights reserved.