如何使用非标准日期格式在Javascript中创建新的Date() [英] How to create a new Date() in Javascript from a non-standard date format

查看:65
本文介绍了如何使用非标准日期格式在Javascript中创建新的Date()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种格式的日期:dd.mm.yyyy

I have a date in this format: dd.mm.yyyy

当我用它实例化一个JavaScript日期时,它给了我一个 NaN

When I instantiate a JavaScript date with it, it gives me a NaN

在c#中,我可以指定一种日期格式,说:这里你有我的字符串,就是这种格式,请做一个日期时间

In c# I can specify a date format, to say: here you have my string, it's in this format, please make a Datetime of it.

这也适用于JavaScript吗?如果没有,有一个简单的方法吗?

Is this possible in JavaScript too? If not, is there an easy way?

我宁愿不使用子字符串表示日期,子字符串表示月份等因为我的方法也必须能够使用德语,意大利语,英语等日期。

I would prefer not to use a substring for day, substring for month etc. because my method must also be capable of german, italian, english etc. dates.

推荐答案

您需要创建一个函数来提取日期部分并将其与< a href =https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date\"rel =noreferrer> 日期 构造函数。

You will need to create a function to extract the date parts and use them with the Date constructor.

请注意,此构造函数将月份视为零基数( 0 = 1月,1 = 2月,...,11 = 12月)。

Note that this constructor treats months as zero based numbers (0=Jan, 1=Feb, ..., 11=Dec).

例如:

function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // note parts[1]-1
  return new Date(parts[2], parts[1]-1, parts[0]);
}

parseDate('31.05.2010');
// Mon May 31 2010 00:00:00

编辑:对于处理变量格式,你可以这样做:

For handling a variable format you could do something like this:

function parseDate(input, format) {
  format = format || 'yyyy-mm-dd'; // default format
  var parts = input.match(/(\d+)/g), 
      i = 0, fmt = {};
  // extract date-part indexes from the format
  format.replace(/(yyyy|dd|mm)/g, function(part) { fmt[part] = i++; });

  return new Date(parts[fmt['yyyy']], parts[fmt['mm']]-1, parts[fmt['dd']]);
}

parseDate('05.31.2010', 'mm.dd.yyyy');
parseDate('31.05.2010', 'dd.mm.yyyy');
parseDate('2010-05-31');

上述函数接受格式参数,该参数应包含 yyyy mm dd 占位符,分隔符并不重要,因为RegExp只捕获了数字。

The above function accepts a format parameter, that should include the yyyy mm and dd placeholders, the separators are not really important, since only digits are captured by the RegExp.

你也可以看看 DateJS ,一个让日期解析无痛的小型库...

You might also give a look to DateJS, a small library that makes date parsing painless...

这篇关于如何使用非标准日期格式在Javascript中创建新的Date()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆