kipris
kipris

Reputation: 3039

Parse from String to DateTime

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?

Upvotes: 0

Views: 161

Answers (2)

Jordi Castilla
Jordi Castilla

Reputation: 26961

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");

Upvotes: 1

xuan hung Nguyen
xuan hung Nguyen

Reputation: 398

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>

Upvotes: 1

Related Questions