JavaScript的等同于.NET的DateTime.Parse [英] Javascript equivalent to .NET's DateTime.Parse

查看:150
本文介绍了JavaScript的等同于.NET的DateTime.Parse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个验证器,将使用DateTime.Parse一个字符串从形式张贴到日期时间转换的.NET的DefaultModelBinder工作。我不希望要等到日期已经被发送到服务器为它意识到这是一个错误的日期。

目前jquery.validate使用以下code,以验证日期字段:

  // http://docs.jquery.com/Plugins/Validation/Methods/date
日期:函数(值,元素){
    返回this.optional(元)|| !/无效|为NaN / .TEST(新日期(值));
}

然而,由于JavaScript的可怕的日期解析器,这样的:


  

275481/69/100089


将评估为有效后,到9月12日,275760.

虽然在另一方面,本


  

二○一三年十一月十九日


将评估为无效

当然,据我所知,C#的DateTime.Parse()需要的东西就像文化(本地化)和闰年考虑在内,并且我可以假设一个固定的(美国)的文化,使2013年2月29日活在客户端上,并踢出在服务器(不理想,但它是可以接受的)。

但我不认为有人不把一个美好的约会验证用C#的DateTime.Parse()的逻辑工作。

也许有人,我只是还没有找到它 - 这就是为什么我在这里发帖

我知道我有几个方法去这一点 - 从非常简单(不准确),以极其复杂的(更准确),但我希望有人已经走了这条道路,发现甜蜜点<。 / p>

解决方案

Datejs 似乎pretty强劲对我来说。其解析功能支持超过150个文化:

  Date.parse(1973年2月20日)

而如果你需要解析日期字符串,是不是在当前区域性有效,你可以使用的 parseExact 功能:

  // 10月15日 -  2004年的日期
Date.parseExact(2004年10月15日,[M / D / YYYY,MMMM D,YYYY]);

I'm trying to build a validator that will work with .NET's DefaultModelBinder of using DateTime.Parse to convert a string from the form post to a DateTime. I don't want to have to wait until a date has been posted to the server for it to realize it was a bad date.

Currently jquery.validate uses the following code to validate date fields:

// http://docs.jquery.com/Plugins/Validation/Methods/date
date: function(value, element) {
    return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
}

However, due to Javascript's terrible Date parser, this:

275481/69/100089

Will evaluate as valid, to Sep. 12, 275760.

While on the other hand, this:

11-19-2013

Will evaluate as invalid.

Of course, I understand that C#'s DateTime.Parse() takes things like culture (localization) and leap year into account, and I could live with assuming a fixed (US) culture, and allowing "02-29-2013" on the client and kick it out at the server (ideally not, but it's acceptable).

But I can't believe someone hasn't put together a better date validator to work with C#'s DateTime.Parse() logic.

Maybe someone has, I just haven't found it -- which is why I'm posting here.

And I know I have several ways to go about this -- from incredibly simple (less accurate) to incredibly complex (more accurate), but I'm hoping someone has already gone down this road and found the sweet spot.

解决方案

Datejs seems pretty robust to me. Its parse function supports over 150 cultures:

Date.parse("February 20th 1973")

And in case you need to parse a date string that is not valid in the current culture you can use the parseExact function:

// The Date of 15-Oct-2004
Date.parseExact("10/15/2004", ["M/d/yyyy", "MMMM d, yyyy"]);

这篇关于JavaScript的等同于.NET的DateTime.Parse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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