Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract date from string using javascript

How does one extract a date from a string using javascript? It can be in the following formats:

31.07.2014

07.31.2014

2014.07.31 the same format but divided by spaces or / or - 31 07 2014 31/07/2014 31-07-2014

the string may contain other character like

Teen.Wolf.S04E06.Orphaned.28.07.2014.HDTV

so how to extract date from these type of name.

I thought of first extracting all the numbers and then comparing if it is greater than 12 to make sure it is month or date. I don't know much about regEx (Regular Expressions) so if it is used please explain a little thank you

like image 575
BluSky Avatar asked Jul 31 '14 13:07

BluSky


People also ask

How to extract date and time from string in JavaScript?

We can use the built-in function toLocaleDateString(). And, if we want to extract both the date and time in a single string, we can use the built-in function toLocaleString().

How to parse the date in JavaScript?

JavaScript Date parse() parse() parses a date string and returns the time difference since January 1, 1970. parse() returns the time difference in milliseconds.

How convert YYYY-MM-DD string to date in JavaScript?

To convert YYYY-MM-DD to MM/DD/YYYY format: Use the split() method to split the string on each hyphen. Add the month , day and year to an array. Join the array elements into a string with a forward slash separator.


2 Answers

Maybe this could help you (Demo Fiddle here):

function getDate(d)
{
    var day, month, year;

    result = d.match("[0-9]{2}([\-/ \.])[0-9]{2}[\-/ \.][0-9]{4}");
    if(null != result) {
        dateSplitted = result[0].split(result[1]);
        day = dateSplitted[0];
        month = dateSplitted[1];
        year = dateSplitted[2];
    }
    result = d.match("[0-9]{4}([\-/ \.])[0-9]{2}[\-/ \.][0-9]{2}");
    if(null != result) {
        dateSplitted = result[0].split(result[1]);
        day = dateSplitted[2];
        month = dateSplitted[1];
        year = dateSplitted[0];
    }

    if(month>12) {
        aux = day;
        day = month;
        month = aux;
    }

    return year+"/"+month+"/"+day;
}
like image 22
lpg Avatar answered Sep 28 '22 00:09

lpg


probably use a regex like

/(\d{4}([.\-/ ])\d{2}\2\d{2}|\d{2}([.\-/ ])\d{2}\3\d{4})/

\d - a digit (equivilant to character class [0-9]
{n} - match n characters
[.\-/ ] - character class matches a single . - / or space (- needs to be escaped because it indicates a range in a character class
\n - a backreference matches the nth match so / will match another / and not a -, /, space or .

you can pull out the first part of the regex and inspect it, it is the same as the second part, except the 4 digits and 2 digits have been swapped

/\d{4}([.\-/ ])\d{2}\1\d{2}/
like image 100
Nick Avatar answered Sep 27 '22 23:09

Nick