0

I'm using JS to pull content from a table and create event list items on a page.

Im using Date.parse to compare the entry date to todays date, and only show events in the future, based on MM/DD/YY value from var eventDate.

<script>
    today       = new Date(); today.setDate(today.getDate() - 1);
    eventDate   = $(this).find("td:nth-child(3)").text().trim();

    if (Date.parse(eventDate) > Date.parse(today)) {
    //Do something...
    }
</script>

I was thrilled to see how simple Date.parse was to use, then realized it only worked in Chrome (not in Firefox or IE). Any other ways to do this cross browser? Any thoughts would be appreciated. Thanks!

Joe White
  • 94,807
  • 60
  • 220
  • 330
trobbins26
  • 219
  • 1
  • 5
  • 13
  • `Date.parse` is available in all browsers, but it expects specific date formats. The [documentation on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse) is pretty comprehensive; give it a look. – Joe White Dec 12 '14 at 05:11
  • see this answer, would be useful http://stackoverflow.com/a/16713809/926333 – Girish Dec 12 '14 at 05:12
  • convert your input to something parse can read before you parse it. regexp helps. – dandavis Dec 12 '14 at 05:38

2 Answers2

1

If you don't mind adding a library to your project; Moment.js provides a comprehensive set of formatting and query functions when handling dates not converted to the Date.parse input. It's fluent interface provides better readability for date comparison:

var dateFormat = "MM/DD/YY";
var today      = moment().subtract(1, "day");
var eventDate  = moment($(this).find("td:nth-child(3)").text().trim(), dateFormat);
if (moment(eventDate).isAfter(today)) {
    // Do something
}
Sparko
  • 735
  • 6
  • 15
  • This seems to be most relevant... I downloaded the library and it seems to at least be outputting something on all browsers now... However, the output is a long number string (1420005600000). Not really sure where this is coming from. Any thoughts? – trobbins26 Dec 16 '14 at 03:40
  • This looks to be outputting an Epoch time format in milliseconds. I'm not sure how you are getting this value, for example `eventDate.valueOf()` would return this. If you have a moment.js object you should be able to use the `.tz` method to convert to a timezone and `.format` for presentation. – Sparko Dec 16 '14 at 11:44
0

You can convert the date format like so:

'01/02/13'.replace(/^(\d{2})\/(\d{2})\/(\d{2})$/, '20$3-$1-$2')
// 2013-01-02
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309