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

查看:62
本文介绍了将 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])

使用正则表达式

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

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

因为你知道你将处理一个由三部分组成的字符串,用连字符分隔.

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

用作:

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

用作:

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

现代 JavaScript

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

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

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

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

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