Javascript 将 dd-mm-yyyy 字符串转换为日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7151543/
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-08-24 01:03:59  来源:igfitidea点击:

Convert dd-mm-yyyy string to date

javascriptdate

提问by user559142

i am trying to convert a string in the format dd-mm-yyyy into a date object in JavaScript using the following:

我正在尝试使用以下方法将 dd-mm-yyyy 格式的字符串转换为 JavaScript 中的日期对象:

 var from = $("#datepicker").val();
 var to = $("#datepickertwo").val();
 var f = new Date(from);
 var t = new Date(to);

("#datepicker").val()contains a date in the format dd-mm-yyyy. When I do the following, I get "Invalid Date":

("#datepicker").val()包含格式为 dd-mm-yyyy 的日期。当我执行以下操作时,我得到“无效日期”:

alert(f);

Is this because of the '-' symbol? How can I overcome this?

这是因为'-'符号吗?我怎样才能克服这个问题?

回答by Adrian Lynch

Split on "-"

在“-”上拆分

Parse the string into the parts you need:

将字符串解析为您需要的部分:

var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])

Use regex

使用正则表达式

var date = new Date("15-05-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "//"))

Why not use regex?

为什么不使用正则表达式?

Because you know you'll be working on a string made up of three parts, separated by hyphens.

因为您知道您将处理由三部分组成的字符串,用连字符分隔。

However, if you were looking for that same string within another string, regex would be the way to go.

但是,如果您要在另一个字符串中查找相同的字符串,则正则表达式将是最佳选择。

Reuse

重用

Because you're doing this more than once in your sample code, and maybe elsewhere in your code base, wrap it up in a function:

因为您在示例代码中多次执行此操作,并且可能在代码库的其他位置执行此操作,所以将其封装在一个函数中:

function toDate(dateStr) {
  var parts = dateStr.split("-")
  return new Date(parts[2], parts[1] - 1, parts[0])
}

Using as:

用作:

var from = $("#datepicker").val()
var to = $("#datepickertwo").val()
var f = toDate(from)
var t = toDate(to)

Or if you don't mind jQuery in your function:

或者,如果您不介意函数中的 jQuery:

function toDate(selector) {
  var from = $(selector).val().split("-")
  return new Date(from[2], from[1] - 1, from[0])
}

Using as:

用作:

var f = toDate("#datepicker")
var t = toDate("#datepickertwo")

Modern JavaScript

现代 JavaScript

If you're able to use more modern JS, array destructuring is a nice touch also:

如果您能够使用更现代的 JS,数组解构也是一个不错的选择:

const toDate = (dateStr) => {
  const [day, month, year] = dateStr.split("-")
  return new Date(year, month - 1, day)
}

回答by epascarello

regular expression example:

正则表达式示例:

new Date( "13-01-2011".replace( /(\d{2})-(\d{2})-(\d{4})/, "//") );

回答by Joe

Another possibility:

另一种可能:

var from = "10-11-2011"; 
var numbers = from.match(/\d+/g); 
var date = new Date(numbers[2], numbers[0]-1, numbers[1]);

Match the digits and reorder them

匹配数字并重新排序

回答by Makah

Using moment.jsexample:

使用moment.js示例:

var from = '11-04-2017' // OR $("#datepicker").val();
var milliseconds = moment(from, "DD-MM-YYYY").format('x');
var f = new Date(milliseconds)

回答by Saad Imran.

var from = $("#datepicker").val(); 
var f = $.datepicker.parseDate("d-m-Y", from);

回答by Prisoner ZERO

You can also write a date inside the parentheses of the Date()object, like these:

您还可以在Date()对象的括号内写入日期,如下所示:

new Date("Month dd, yyyy hh:mm:ss")
new Date("Month dd, yyyy")
new Date(yyyy,mm,dd,hh,mm,ss)
new Date(yyyy,mm,dd)
new Date(milliseconds)

回答by Diodeus - James MacFarlane

Use this format: myDate = new Date('2011-01-03'); // Mon Jan 03 2011 00:00:00

使用这种格式: myDate = new Date('2011-01-03'); // Mon Jan 03 2011 00:00:00

回答by argene santoni

In my case

就我而言

new Date("20151102034013".replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/, "--T::"))

Result: Mon Nov 02 2015 04:40:13 GMT+0100 (CET) then I use .getTime() to work with milliseconds

结果:Mon Nov 02 2015 04:40:13 GMT+0100 (CET) 然后我使用 .getTime() 来处理毫秒

回答by James Hibbard

The accepted answer kinda has a bug

接受的答案有点错误

var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])

Consider if the datepicker contains "77-78-7980" which is obviously not a valid date. This would result in:

考虑日期选择器是否包含显然不是有效日期的“77-78-7980”。这将导致:

var f = new Date(7980, 77, 77);
=> Date 7986-08-15T22:00:00.000Z

Which is probably not the desired result.

这可能不是想要的结果。

The reason for this is explained on the MDNsite:

原因在MDN站点上有解释:

Where Date is called as a constructor with more than one argument, if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013, 13, 1)is equivalent to new Date(2014, 1, 1).

当 Date 作为具有多个参数的构造函数被调用时,如果值大于它们的逻辑范围(例如,提供 13 作为月份值或 70 作为分钟值),则将调整相邻的值。例如new Date(2013, 13, 1)相当于new Date(2014, 1, 1)



A better way to solve the problem is:

解决问题的更好方法是:

const stringToDate = function(dateString) {
  const [dd, mm, yyyy] = dateString.split("-");
  return new Date(`${yyyy}-${mm}-${dd}`);
};

console.log(stringToDate('04-04-2019'));
// Date 2019-04-04T00:00:00.000Z

console.log(stringToDate('77-78-7980'));
// Invalid Date

This gives you the possibility to handle invalid input.

这使您可以处理无效输入。

For example:

例如:

const date = stringToDate("77-78-7980");

if (date === "Invalid Date" || isNaN(date)) {
  console.log("It's all gone bad");
} else {
  // Do something with your valid date here
}

回答by wesbos

You can use an external library to help you out.

您可以使用外部库来帮助您。

http://www.mattkruse.com/javascript/date/source.html

http://www.mattkruse.com/javascript/date/source.html

getDateFromFormat(val,format);

Also see this: Parse DateTime string in JavaScript

另请参阅:在 JavaScript 中解析日期时间字符串