JavaScript 将字符串转换为日期格式 (dd mmm yyyy),即 2012 年 6 月 1 日
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17445585/
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
JavaScript convert string into Date with format (dd mmm yyyy) i.e. 01 Jun 2012
提问by Satinder singh
I am getting a string variable having date in format 6/1/2012
, I want to convert it into 01 Jun 2012
.
JS FIDDLE DEMO
我得到了一个日期格式的字符串变量6/1/2012
,我想将它转换为01 Jun 2012
.
JS小提琴演示
Code I tried:
我试过的代码:
var t_sdate="6/1/2012";
var sptdate = String(t_sdate).split("/");
var myMonth = sptdate[0];
var myDay = sptdate[1];
var myYear = sptdate[2];
var combineDatestr = myYear + "/" + myMonth + "/" + myDay;
var dt = new Date(combineDatestr);
var formatedDate= dt.format("dd mmm yyyy")
alert(formatedDate);
Getting output as 01 000 2012
, required as 01 Jun 2012
获取输出为01 000 2012
,需要为01 Jun 2012
回答by Chickenrice
Try this:
试试这个:
function getFormattedDate(input) {
var pattern = /(.*?)\/(.*?)\/(.*?)$/;
var result = input.replace(pattern,function(match,p1,p2,p3){
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
return (p2<10?"0"+p2:p2) + " " + months[(p1-1)] + " " + p3;
});
alert(result);
}
getFormattedDate("6/1/2013");
回答by sohaiby
Since other users already mentioned that "format"
is not a standard method of Date object. You can do it without using any format method (even if there exist any)
由于其他用户已经提到这 "format"
不是 Date 对象的标准方法。您可以在不使用任何格式方法的情况下执行此操作(即使存在任何格式)
var t_sdate = "6/1/2012";
var sptdate = String(t_sdate).split("/");
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var myMonth = sptdate[0];
var myDay = sptdate[1];
var myYear = sptdate[2];
var combineDatestr = myDay + " " + months[myMonth - 1] + " " + myYear;
alert(combineDatestr);
回答by DhMi
return $.datepicker.formatDate('dd-M-yy', new Date(dateVal)); //01-Dec-2014
回答by Milton
You may want to use javascript Intl https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
您可能想使用 javascript Intl https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
The following example will show something like Nov 02, 2017
以下示例将显示类似 Nov 02, 2017
console.log(new Intl.DateTimeFormat('en-EN', { year: 'numeric', month: 'short', day: 'numeric' }).format(new Date()));
console.log(new Intl.DateTimeFormat('en-EN', { year: 'numeric', month: 'short', day: 'numeric' }).format(new Date()));
Milton.-
米尔顿.-
回答by guy777
"format" is not a standard method of Date object
“格式”不是 Date 对象的标准方法
回答by satish
dt.format("dd MMM yyyy")
Use capital letters.
使用大写字母。