Javascript 在 jquery 中转换日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26549773/
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
Convert date format in jquery
提问by Nasser
I need the date to show in this format 2014-11-04 as "yy mm dd"
我需要以这种格式 2014-11-04 显示的日期为“yy mm dd”
Currently, my script still shows me Tue Nov 04 2014 00:00:00 GMT+0200 (Egypt Standard Time)
目前,我的脚本仍然向我显示 Tue Nov 04 2014 00:00:00 GMT+0200(埃及标准时间)
$(document).ready(function() {
var userDate = '04.11.2014';
from = userDate.split(".");
f = new Date(from[2], from[1] - 1, from[0]);
console.log(f);
});
回答by Jared Smith
You can construct this using the date object's methods
您可以使用日期对象的方法来构造它
var date = new Date(userDate),
yr = date.getFullYear(),
month = date.getMonth() < 10 ? '0' + date.getMonth() : date.getMonth(),
day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(),
newDate = yr + '-' + month + '-' + day;
console.log(newDate);
回答by CodeGodie
You may try the following:
您可以尝试以下操作:
$(document).ready(function() {
var userDate = '04.11.2014';
var from = userDate.split(".");
var f = new Date(from[2], from[1], from[0]);
var date_string = f.getFullYear() + " " + f.getMonth() + " " + f.getDate();
console.log(date_string);
});
Alternatively I would look into Moment.jsIt would be way easier to deal with dates:
或者,我会研究 Moment.js处理日期会更容易:
$(document).ready(function() {
var userDate = '04.11.2014';
var date_string = moment(userDate, "DD.MM.YYYY").format("YYYY-MM-DD");
$("#results").html(date_string);
});
MOMENT.JS DEMO: FIDDLE
MOMENT.JS 演示:小提琴
回答by ThunD3eR
I think you might find you answer here: Converting string to date in js
我想你可能会在这里找到答案: Converting string to date in js
Replace the "." with "-" to validate the date.
更换 ”。” 用“-”来验证日期。
Edit: this is done in javascript, Jquery does not have a utillity function for date
编辑:这是在 javascript 中完成的,Jquery 没有日期的实用函数

