Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

javascript - 将dd-mm-yyyy字符串转换为日期(Convert dd-mm-yyyy string to date)

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.

(("#datepicker").val()包含格式为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?

(我该如何克服?)

  ask by user559142 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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})/, "$2/$1/$3"))

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...