简体   繁体   中英

How do I construct a javascript Date object from string

I have the date value "06/12/2012" in string format. How do I construct a Javascript Date object, so that I can perform before/after comparisons?

The only reliable way to turn a string in to a date object is to parse it. You must know the format before hand. The string "06/12/2012" does not conform to any formal standard, though is most likely to be day/month/year, so:

// Convert string in d/m/y format to a Date object
function toDate(s) {
  var bits = s.split('/');
  return new Date(bits[2],--bits[1],bits[0]);
}

Note that any date parsing function must be told the format and (usually) seperator, since guessing the format is extremely error prone.

Do not pass the string to any browser Date object and rely on the host correctly interpreting it, the only format browsers might recognise is ISO8601 format, and even then many get it wrong.

var d = new Date("06/12/2012");

I think this can help you http://www.mattkruse.com/javascript/date/

There is a getDateFromFormat() function that you can tweak a little to solve your problem.

var date = new Date("06/12/2012"),
    other = new Date("03/12/2012");

(date - other > 0? alert("after") : alert("before");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM