0

I have the below date which I need to convert to 'dd/MM/yyyy' and 'HH:mm'. How can I achieve this without using getHours() or moment.js (Most of the answers are using either of these)?

2017-11-24T16:05:00Z

Saif Ahmad
  • 1,118
  • 1
  • 8
  • 24
  • 1
    Just reformat the string, no need to create a Date. But there are many questions already on [*parsing ISO format strings*](https://stackoverflow.com/search?q=%5Bjavascript%5D+how+to+parse+ISO+format+string) and then [*formatting a date*](https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript). – RobG Dec 01 '17 at 05:38

4 Answers4

2

If you are looking for customization then below code will help you

var dt='2017-11-24T16:05:00Z'
dtArray=dt.split('T')
dateArray=dtArray[0].split('-') //dtArray[0] manupulating date
result = dateArray.reverse().join('/')
console.log(result) //"24/11/2017"

similar way you do for HH:MM

time=dtArray[1].split(':').slice(0,2).join(':')
Jaydip Jadhav
  • 12,179
  • 6
  • 24
  • 40
  • All those array methods… consider `var b = dt.split(/\D/); result = b[2]+'/'+b[1]+'/'+b[0]`. ;-) – RobG Dec 01 '17 at 06:01
0

You can use regex groups :

var myDate = "2017-11-24T16:05:00Z";
var myRegexp = /(\d\d\d\d)-(\d\d)-(\d\d)/
var match = myRegexp.exec(myDate);
var formattedDate = `${match[3]}/${match[2]}/${match[1]}`
alert(formattedDate);
Alex Lavriv
  • 321
  • 1
  • 10
0

step 1 create new ISO string and extract Date in yyyymmdd

var data = new Date().toISOString().substring(0, 10);

step2 split from '-'

var date = data.split('-');

step 3 arrange the way you want

var newDate = date[2] +'-'+ date[1] +'-'+ date[0]

same as for HH:mm

new Date().toISOString().substring(11, 16);
Jigar
  • 1,314
  • 9
  • 19
-1

You can user date-fns js library in which you just need to do this.

import {format} from 'date-fns';
const date = format(new Date(), 'DD/MM/YYYY');
const time = format(new Date(), 'HH:mm');

console.log(date) => 30/11/2017
console.log(time) => 11:17
Harish Soni
  • 1,796
  • 12
  • 27
  • Your answer shouldn't rely on a library that isn't tagged or mentioned in the OP. Is there really a "fomrat" method? ;-) – RobG Dec 01 '17 at 06:03