1

I use this method in order to convert a date string to a javascript date object:

function convertToDateOrUndefined(dateString) {
    if (dateString instanceof Date || dateString == null) { 
        return undefined;
    }
    return new Date(dateString.replace(/(\d{2})\.(\d{2})\.(\d{4})/,'$3-$2-$1'));
}

Currently I have this dateTime string 'dd.MM.yyyy HH:mm' and I would need also a function to convert this string into a js date obejct. I am not really good in regex therefore I would need help - Thanks!

2 Answers 2

1

Look at the current regex. You know it returns a date from your dd.MM.yyyy format, right? So you can assume that the three (\d{n}) represent the day, month and year (\d means a digit, {n} means n times, so \d{2} mean two digits; the () groups each part so we can refer to them later).

In the second string, we take the parts the we got from the 1st one, and reorder them. $1 is the 1st group (the part of the regex inside the ()), $2 is the 2nd group, etc.

From there, the way to the solution is simple. We just need to add the time part:

new Date(dateString.replace(/(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2})/,'$3-$2-$1 $4:$5'));
Sign up to request clarification or add additional context in comments.

Comments

0

A non regex solution. Hope this helps

var dateString = '25.12.2016 00:00';
var formattedDateString  = dateString.split(' ')[0].split('.').reverse().join('-');

var dateObj = new Date(formattedDateString);

console.log(dateObj);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.