0

I want to make a userscript for a website, where I want to extract and select the date in some <td> fields. Example:

<tbody>
<td><img></td>
<td>something</td>
<td>something</td>
...
<td style="text-align:center;">2016-02-10 13:27</td>
<td>something</td>
...
<td>something</td>
</tbody>

There are two things I want to do: 1. compare the date with another stored date (and check if it is later). 2. change the background-color of the <td> element where the date is located.

This is what I have, and it returns an empty array...

var dateArray = [];
$("td").each(function(){
    if(String(this).match(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}/)){
        dateArray.push(this);
    }
});

What is wrong and/or what could I do in a better way?

Thanks!

5
  • I guess this will be a jQuery object, what you do you expect String(this) to return? You might try this.text() instead (see API doco: .text()). Commented Mar 17, 2016 at 22:28
  • Yes, it was an object first, that's why I did the String(this), so I could do the .match to extract the date Commented Mar 17, 2016 at 22:30
  • String(object) will call the object's toString method. I don't think jQuery sets a specific method, so you'll get the built–in Object.prototype.toString , which is probably returning something like [object Object]. Commented Mar 17, 2016 at 22:32
  • 1
    Also note that if you intend converting "2016-02-10 13:27" to a date, then you'll need to parse it manually (a library can help but it only needs a 2 line function). That format isn't one supported by ECMAScript 2015, so parsing is implementation dependent. Some will treat it as UTC, some as local and the rest as invalid. Commented Mar 17, 2016 at 22:37
  • You were right about the [object Object] return! Didn't noticed that... Thanks! I also didn't know about the converting problem, have to check that out, good to know. Commented Mar 17, 2016 at 22:42

1 Answer 1

0

You could also try to create a date object. And check whether a valid date was created

var date = new Date($(this).text());
if (isNaN(date.getTime())) {
  // invalid date
} else {
  // valid date
}
Sign up to request clarification or add additional context in comments.

4 Comments

Works as a charm, thank you! I changed it to (!isNaN(date.getTime())), because I only need the valid dates.
Oh, and there is a ) missing after (isNaN(date.getTime())
Please don't recommend parsing strings with the Date constructor, it's unreliable (to say the least).
Thanks @RobG I'll keep that in mind

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.