如何使用 JavaScript 或 jQuery 解析“dd/mm/yyyy”或“dd-mm-yyyy”或“dd-mmm-yyyy”格式的日期字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10430321/
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
how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery
提问by Sharanamma Jekeen
Possible Duplicate:
Extending JavaScript's Date.parse to allow for DD/MM/YYYY (non-US formatted dates)?
Convert dd-mm-yyyy string to date
可能的重复:
扩展 JavaScript 的 Date.parse 以允许 DD/MM/YYYY(非美国格式的日期)?
将 dd-mm-yyyy 字符串转换为日期
Entered a date in textbox, for example: 05/09/1985, and I wanted to convert it to 05-Sep-1985(dd-MMM-yyyy) format. How would I achieve this? Note that the source format may be dd-mm-yyyy
or dd/mm/yyyy
or dd-mmm-yyyy
format.
在文本框中输入日期,例如:05/09/1985,我想将其转换为05-Sep-1985(dd-MMM-yyyy) 格式。我将如何实现这一目标?请注意,源格式可以是dd-mm-yyyy
或dd/mm/yyyy
或dd-mmm-yyyy
格式。
Code Snippet:
代码片段:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val());
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
This code returns 09-May-1985but I want 05-Sep-1985. Thanks.
此代码返回09-May-1985但我想要05-Sep-1985。谢谢。
回答by
You might want to use helper library like http://momentjs.com/which wraps the native javascript date object for easier manipulations
您可能想要使用像http://momentjs.com/这样的辅助库,它包装了原生 javascript 日期对象以便于操作
Then you can do things like:
然后,您可以执行以下操作:
var day = moment("12-25-1995", "MM-DD-YYYY");
or
或者
var day = moment("25/12/1995", "DD/MM/YYYY");
then operate on the date
然后在日期上操作
day.add('days', 7)
and to get the native javascript date
并获取本机 javascript 日期
day.toDate();
回答by T.J. Crowder
Update
更新
Below you've said:
你在下面说过:
Sorry, i can't predict date format before, it should be like dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format finally i wanted to convert all this format to dd-MMM-yyyy format.
抱歉,我之前无法预测日期格式,它应该是 dd-mm-yyyy 或 dd/mm/yyyy 或 dd-mmm-yyyy 格式,最后我想将所有这些格式转换为 dd-MMM-yyyy 格式。
That completelychanges the question. It'll be much more complex if you can't control the format. There is nothing built into JavaScript that will let you specify a date format. Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd
, although in practice almost all browsers also support yyyy/mm/dd
as well. But other than that, you have to write the code yourself or (and this makes much more sense) use a good library. I'd probably use a library like moment.jsor DateJS(although DateJS hasn't been maintained in years).
这完全改变了问题。如果你不能控制格式,它会复杂得多。JavaScript 中没有任何内容可以让您指定日期格式。正式地,JavaScript 支持的唯一日期格式是ISO-8601:的简化版本yyyy-mm-dd
,但实际上几乎所有浏览器也支持yyyy/mm/dd
。但除此之外,您必须自己编写代码或(这更有意义)使用一个好的库。我可能会使用像moment.js或DateJS这样的库(尽管 DateJS 已经多年没有维护了)。
Original answer:
原答案:
If the format is alwaysdd/mm/yyyy
, then this is trivial:
如果格式总是dd/mm/yyyy
,那么这是微不足道的:
var parts = str.split("/");
var dt = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[0], 10));
split
splits a string on the given delimiter. Then we use parseInt
to convert the strings into numbers, and we use the new Date
constructor to build a Date
from those parts: The third part will be the year, the second part the month, and the first part the day. Date
uses zero-based month numbers, and so we have to subtract one from the month number.
split
在给定的分隔符上拆分字符串。然后我们使用parseInt
将字符串转换为数字,并使用new Date
构造函数Date
从这些部分构建一个:第三部分是年,第二部分是月份,第一部分是天。Date
使用从零开始的月份数字,因此我们必须从月份数字中减去一。
回答by Jon
Date.parse
recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy
, so the result is wrong.
Date.parse
仅识别特定格式,您无法告诉它您的输入格式是什么。在这种情况下它认为输入是格式mm/dd/yyyy
,所以结果是错误的。
To fix this, you need either to parse the input yourself (e.g. with String.split
) and then manually constructa Date
object, or use a more full-featured library such as datejs.
要解决此问题,您需要自己解析输入(例如使用String.split
),然后手动构造一个Date
对象,或者使用功能更全面的库,例如datejs。
Example for manual parsing:
手动解析示例:
var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
Example using date.js:
使用 date.js 的示例:
var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");
回答by Paulo H.
Try this:
尝试这个:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'/'));
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1')
change day/month position.
RegExp 替换.replace(/([0-9]+)\/([0-9]+)/,'$2/$1')
更改日/月位置。
回答by Ankur Verma
See this http://blog.stevenlevithan.com/archives/date-time-format
看到这个http://blog.stevenlevithan.com/archives/date-time-format
you can do anything with date.
你可以用日期做任何事情。
file : http://stevenlevithan.com/assets/misc/date.format.js
文件:http: //stevenlevithan.com/assets/misc/date.format.js
add this to your html code using script tag and to use you can use it as :
使用脚本标记将此添加到您的 html 代码中,并使用它作为:
var now = new Date();
now.format("m/dd/yy");
// Returns, e.g., 6/09/07