0

I have a date in format YYYYMMDDTHHMMSS and need to get the date in format DD.MM.YYYY HH:MM:SS . I do such:

var dateTimeFormat;
var dateAsString = dataTimeFormat.split('', dateTimeFormat.lenght);
var year = dateAsString.splice(0, 4).join('');
var month = dateAsString.splice(0, 2).join('');
var day = dateAsString.splice(0, 2).join('');
var hours = dateAsString.splice(1, 2).join('');
var minutes = dateAsString.splice(1, 2).join('');
var seconds = dateAsString.splice(1, 2).join('');
var date = day + '.' + month + '.' + year + ' ' + hours + ':' + minutes + ':' + seconds;
return date;

But how can I convert date to Date format?

2 Answers 2

1

After transforming string into a known format, Date::parse() will be enough:

var yourDate = new Date(Date.parse(date));

WORKING DEMO:

var date = "2016.06.15 10:10:10";
var yourDate = new Date(Date.parse(date));
alert(yourDate);

NOTE: your format is a bit weird, but maybe parse will accept it as long as it accept many string formats such as:

Date.parse("Aug 9, 1995");
Date.parse("Wed, 09 Aug 1995 00:00:00");
Date.parse("Wed, 09 Aug 1995 00:00:00 GMT");
Sign up to request clarification or add additional context in comments.

5 Comments

I think parse function is excessive, you can pass date string directly in new date.
Thanks, but I confused a bit. I need to show the date in a table and then sort by date. I did that script you adviced and I get this imgur.com/or3bTOa . I think I need to leave the date as string and then write sort function to compare separately years, months, dates, etc ?
IMHO is better to sort an array of Dates. Check this answer and this documentation
I used your code but not always the function returns 'Invalid Date {}' . What's wrong?
It happens because the string parsed is not correct date, check valid formats here
1

i think this is easy way to do this =). hope it help

    <script>
        dateTimeFormat = '20161506T112130';
        str = dateTimeFormat.split("");
        date = str[0] + str[1] + str[2] + str[3] + '.' + str[4] + str[5] + '.' + str[6] + str[7] + ' ' + str[9] + str[10] + ':' + str[11] + str[12] + ':' + str[13] + str[14];
    console.log(date);
    </script>

2 Comments

i didn't see "But how can I convert date to Date format?", that's make me think his code is don't run and i code this for him. I didn't want to ridicule him.
you are not converting to Date as OP demands, you only transform String format

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.