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

Categories

I have a string that contains 8 digits that represent a date. For example:

20120515

I'd like to compare it with today's date, created in this manner:

var currentDate = new Date();

How can I convert the "8 digit date string" to a suitable date format in order to compare it to currentDate?

See Question&Answers more detail:os

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

1 Answer

Use the substring method and substring off 4 elements and assign it to your new date for the year. Then substring off two elements at a time and store the month and date accordingly.

var dateString  = "20120515";
var year        = dateString.substring(0,4);
var month       = dateString.substring(4,6);
var day         = dateString.substring(6,8);

var date        = new Date(year, month-1, day);
var currentDate = new Date();

Now you can compare the two dates with the normal operators.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...