Reputation: 6127
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.
Upvotes: 2
Views: 1620
Reputation: 147503
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
Upvotes: 3
Reputation: 1533
Use the Date
object's toDateString() method instead of its toString() method.
Even so, it might be better to compare the two date objects directly: Compare two dates with JavaScript
Upvotes: 2