omega
omega

Reputation: 43913

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?

Upvotes: 0

Views: 119

Answers (3)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241808

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

Upvotes: 0

Kevin
Kevin

Reputation: 1992

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

Upvotes: 0

Rob Johnstone
Rob Johnstone

Reputation: 1734

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

Upvotes: 2

Related Questions