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?

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
kipris
  • 2,899
  • 3
  • 20
  • 28

2 Answers2

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>
xuan hung Nguyen
  • 390
  • 3
  • 12
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");
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • 1
    I think parse function is excessive, you can pass date string directly in new date. – z1m.in Jun 15 '16 at 08:00
  • 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 http://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 ? – kipris Jun 15 '16 at 08:08
  • 1
    IMHO is better to sort an array of `Dates`. Check [this answer](http://stackoverflow.com/a/19430819/3850595) and [this documentation](http://www.w3schools.com/jsref/jsref_sort.asp) – Jordi Castilla Jun 15 '16 at 08:11
  • I used your code but not always the function returns 'Invalid Date {}' . What's wrong? – kipris Jun 15 '16 at 11:39
  • It happens because the string parsed is not correct date, check valid formats [here](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Date/parse) – Jordi Castilla Jun 15 '16 at 11:46