将dd-mm-yyyy字符串转换为日期 [英] Convert dd-mm-yyyy string to date

查看:135
本文介绍了将dd-mm-yyyy字符串转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

alert(f);

这是因为 - 符号吗?如何克服这个问题?

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

推荐答案

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

Parse the string into the parts you need:

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

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

因为你知道你会使用一个由三个部分组成的字符串,用连字符分隔。

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.

重用

由于您在示例代码中以及代码库中的其他地方不止一次地执行此操作,因此将其包含在函数中:

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]);
}

使用as:

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

或者如果您不介意jQuery的功能:

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

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

使用as:

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

这篇关于将dd-mm-yyyy字符串转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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