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.

wanovak
  • 6,117
  • 25
  • 32
  • 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 http://www.datejs.com/. – Martin-Brennan Aug 13 '12 at 01:33
  • @Martin-Brennan Thanks, but it failed when I tried entering the initial format into the 'Mad Skillz' box. – wanovak Aug 13 '12 at 01: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. – Martin-Brennan Aug 13 '12 at 01:54
  • What format is your "other" date in? You would be best off getting them both to date objects rather than strings. – westo Aug 13 '12 at 02:06

2 Answers2

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

RobG
  • 142,382
  • 31
  • 172
  • 209
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

Community
  • 1
  • 1
Alex Kalicki
  • 1,533
  • 9
  • 20
  • No, don't do that. It is completely implementation dependent and not consistent across browsers. W3Schools is a very poor reference, the [ECMAScript standard](http://es5.github.com/#x15.9.5.5) is definitive. – RobG Aug 13 '12 at 03:00