noobinmath
noobinmath

Reputation: 185

Reactjs Timezone convertion

I am connected mssql database and get some informations includes Date_Time.

Time is coming like 2021-01-30T15:08:25.357Z. I want to convert it to dd-mm-yy hh:mm:ss format. So, it should be 30-01-2021 15:08:25.

I used this method but it is not exactly that I want.

 var d1 = new Date(datey).toLocaleDateString("tr")
  var newTime=d1+" "+
  new Date(datey).getUTCHours()+":"+
  new Date(datey).getUTCMinutes()+":"+
  new Date(datey).getUTCSeconds()
  // it returns 30/01/2021 15:8:25

Maybe, In there, I want to see time fomat with 0 such as 15:08. When hour 2 a.m it just 2:0 but I want to see it 02:00.

How should I do , is there any idea?

Upvotes: 1

Views: 60

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30675

I would suggest using a date/time library such as moment.js, this will make date manipulation much easier, parsing and formatting your date is then very simple:

const input= "2021-01-30T15:08:25.357Z";
console.log("Input date:", input);

// To convert the date to local before displaying, we can use moment().format()
const formattedDateLocal = moment(input).format("DD-MM-YY HH:mm:ss");
console.log("Formatted date (Local Time):", formattedDateLocal );

// To display the UTC date, we can use moment.utc().format()
const formattedDateUTC = moment.utc(input).format("DD-MM-YY HH:mm:ss");
console.log("Formatted date (UTC):", formattedDateUTC );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Upvotes: 1

Related Questions