Home > Software engineering >  How to extract date and time from ISO into local date and time
How to extract date and time from ISO into local date and time

Time:10-27

I have a date and time in ISO

"time": "2021-10-28T17:30:00.000Z"

Below is what I am doing right now to extract the date and time:

var dateExtract = time.substring(0, 10);
var timeExtract = time.match(/\d\d:\d\d/);

But it is giving me the exact date and time written in ISO.

What I want is to extract the date and time in local date and time. I don't know how to do this.

CodePudding user response:

let obj = {"time": "2021-10-28T17:30:00.000Z"}
const dateTime = new Date(obj.time);
const date  = dateTime.toLocaleDateString().replace(/\//g, '-');
// '28-10-2021'
const time = dateTime.toLocaleTimeString()
// '18:30:00' since I am in ( 1)

CodePudding user response:

Just create a date object and use toLocaleString or toLocaleDateString or toLocaleTimeString

const date = new Date("2021-10-28T17:30:00.000Z")
console.log(date.toLocaleString())
console.log(date.toLocaleDateString())
console.log(date.toLocaleTimeString())
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You are getting dates in a wrong method. when you are reading the date it should be converted to your locale, so that you will get exact date from UTC date

You can use JS Date() function or moment library

let d = new Date("2021-10-28T17:30:00.000Z")

d.toDateString()

d.toLocaleDateString()

check Date functions to get date, month, year, time , seconds or timestamp

refer How to format a JavaScript date

https://www.w3schools.com/js/js_dates.asp

https://www.w3schools.com/js/js_date_formats.asp

Or you can use the external moment library https://momentjs.com/

  • Related