2

I'm trying to truncate a JavaScript Date object string from:

Wed Aug 01 2012 06:00:00 GMT-0700 (Pacific Daylight Time)

to

Wed Aug 01 2012

(I'm not particular, could be of format MM/DD/YYYY for example, as long as I get rid of the time/timezone)

Essentially I just want to get rid of the time and the timezone because I need to do a === comparison with another date (that doesn't include the time or timezone)

I've tried using this http://www.mattkruse.com/javascript/date/index.html but it was to no avail. Does anyone know how I can format the existing string such as to get rid of the time? I would prefer to stay away from substring functions, but if that's the only option then I guess I'll have to settle.

Edit: I'm open to options that will compare two date objects/strings and return true if the date is the same and the time is different.

4
  • You could try out date.js as well, it's a library that lets you do stuff like just get the date out of a full Date() object datejs.com. Commented Aug 13, 2012 at 1:33
  • @Martin-Brennan Thanks, but it failed when I tried entering the initial format into the 'Mad Skillz' box. Commented Aug 13, 2012 at 1:40
  • It should work if you get rid of the (Pacific Daylight Time) part of it, but I'm not sure if you need that for what you're using it for. Commented Aug 13, 2012 at 1:54
  • What format is your "other" date in? You would be best off getting them both to date objects rather than strings. Commented Aug 13, 2012 at 2:06

2 Answers 2

3

The only way to get a specific format of date across different browsers is to create it yourself. The Date methods in ECMAScript are all implementation dependent.

If you have a date object, then:

// For format Wed Aug 01 2012
function formatDate(obj) {
  var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  var months = ['Jan','Feb','Mar','Apr','May','Jun',
               'Jul','Aug','Sep','Oct','Nov','Dec'];    
  return days[obj.getDay()] + ' ' + months[obj.getMonth()] + 
         ' ' + obj.getDate() + ' ' + obj.getFullYear();
}

Though a more widely used format is Wed 01 Aug 2012

Sign up to request clarification or add additional context in comments.

Comments

2

Use the Date object's toDateString() method instead of its toString() method.

SIDE BY SIDE DEMO

Even so, it might be better to compare the two date objects directly: Compare two dates with JavaScript

1 Comment

No, don't do that. It is completely implementation dependent and not consistent across browsers. W3Schools is a very poor reference, the ECMAScript standard is definitive.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.