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!

RobG
  • 142,382
  • 31
  • 172
  • 209
BenjaVR
  • 530
  • 5
  • 15
  • 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()*](http://api.jquery.com/text/)). – RobG Mar 17 '16 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 – BenjaVR Mar 17 '16 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]*. – RobG Mar 17 '16 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. – RobG Mar 17 '16 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. – BenjaVR Mar 17 '16 at 22:42

1 Answers1

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
}
gabesoft
  • 1,228
  • 9
  • 6