简体   繁体   中英

How to get date difference with specific date format?

In my javascript code, I am able to only get the date as a string in this format: Example: Mon May 28 11:20:46 EDT 2012 .

Is there a way I can check if that date and the current date is >= than 1 week?

Just subtract them

var today = new Date(),
    test = new Date(dateString);

if (today - test > (7 * 24 * 60 * 60 * 1000)) { // time is in milliseconds
  console.log('more than a week ago');
}

Just initiate a Date object using your date string and compare its timestamp with today's

var d1 = new Date("Mon May 10 11:20:46 EDT 2013");
alert((new Date()) - d1 >=  (7 * 24 * 60 * 60 * 1000));

You should understand that time zone abbreviations are not guaranteed to be unique. Parsing a date string that has a time zone abbreviation could be dangerous. For example, how do you know that CST would mean "Central Standard Time" in the USA, and not "China Standard Time"? See this list of abbreviations and you'll find many different time zones that have the same letters when abbreviated.

Most browsers will make some assumptions based on your local zone. But you probably don't want to rely on this.

Also, not every browser will support parsing the format you have. If you're stuck with this format, you should consider using moment.js to parse the date string. You still have the time zone issue to contend with though.

Moment.js also some great features that would help you out:

var now = moment();
if (now >= moment(yourDate).add('weeks', 1))
{
    ...
}

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