Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 在JavaScript中将字符串转换为日期(Converting a string to a date in JavaScript)

How can I convert a string to a date in JavaScript?

(如何在JavaScript中将字符串转换为日期?)

var st = "date in some format"
var dt = new date();

var dt_st= //st in date format same as dt
  ask by jslearner translate from so

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

1 Answer

0 votes
by (71.8m points)

The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.

(字符串解析的最佳字符串格式是日期ISO格式以及JavaScript Date对象构造函数。)

Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS .

(ISO格式的示例: YYYY-MM-DDYYYY-MM-DDTHH:MM:SS 。)

But wait!

(可是等等!)

Just using the "ISO format" doesn't work reliably by itself.

(仅仅使用“ ISO格式”本身不能可靠地工作。)

String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version).

(字符串有时会解析为UTC,有时会解析为本地时间(基于浏览器供应商和版本)。)

The best practice should always be to store dates as UTC and make computations as UTC.

(最佳做法应始终是将日期存储为UTC并进行计算为UTC。)

To parse a date as UTC, append a Z - eg: new Date('2011-04-11T10:20:30Z') .

(要将日期解析为UTC,请附加Z ,例如: new Date('2011-04-11T10:20:30Z') 。)

To display a date in UTC, use .toUTCString() ,

(要以UTC显示日期,请使用.toUTCString() ,)
to display a date in user's local time, use .toString() .

(要显示用户当地时间的日期,请使用.toString() 。)

More info on MDN |

(有关MDN的更多信息|)

Date and this answer .

(日期这个答案 。)

For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, eg: new Date('2011', '04' - 1, '11', '11', '51', '00') .

(为了与旧版本的Internet Explorer兼容(小于9的IE版本在Date构造函数中不支持ISO格式),应将datetime字符串表示形式拆分为其各个部分,然后可以使用带datetime组成部分的构造函数,例如: new Date('2011', '04' - 1, '11', '11', '51', '00') 。)

Note that the number of the month must be 1 less.

(请注意,月份数必须少1。)


Alternate method - use an appropriate library:

(替代方法-使用适当的库:)

You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.

(您还可以利用Moment.js库,该库允许解析具有指定时区的日期。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...