0

I am getting created_at timestamp from backend in UTC format, which i need to render in browser. I am using date pipe in Angular-7. After reading few blogs and stackoverflow, i wrote this function below to get normal date format, which i can pass through date pipe in angular to format.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC

  • Issue: The output is in future date.
  • Input: "22-12-2020 03:44:09 UTC"
  • Output: "Fri Jan 22 2021 09:14:09 GMT+0530 (India Standard Time)"

getDateFromUTC(dateString: string) {
    const date = dateString
      .split(" ")[0]
      .split("-")
      .map((number) => parseInt(number));
    const hours = dateString
      .split(" ")[1]
      .split(":")
      .map((num) => parseInt(num));

    const convertedDate = new Date(
Date.UTC(date[2], date[1], date[0], hours[0], hours[1],hours[2])
    );
    return convertedDate;
}
getDateFromUTC("22-12-2020 03:44:09 UTC")

What am i doing wrong?

Raj
  • 1,100
  • 3
  • 20
  • 33
  • UTC dates are automatically converted to local time (a JS Date object) based on your browsers timezone. No conversion should be necessary. Double check if the back-end is returning UTC correctly. – Michael Kang Dec 28 '20 at 09:12
  • Ok. So i am formatting the date in a certain format in Angular using [date pipe](https://angular.io/api/common/DatePipe) as `created_at: {{ time | date:'medium' }}`. Using UTC value directly in the template is giving "invalid date" error. – Raj Dec 28 '20 at 09:16
  • 1
    UTC ends in a 'Z'. It looks like your BE is not returning standard ISO UTC. Assuming the value is correct, then it should be: 2020-12-22T03:44:09.000Z – Michael Kang Dec 28 '20 at 13:32
  • Got it. This was an error on the backend part. thanks – Raj Dec 30 '20 at 16:06

4 Answers4

1

Months in date object start from 0. So your code should decrease month by 1. Refer here.

Date.UTC(date[2], date[1] - 1, date[0], hours[0], hours[1],hours[2])

function getDateFromUTC(dateString) {
  const date = dateString
    .split(" ")[0]
    .split("-")
    .map((number) => parseInt(number));
  const hours = dateString
    .split(" ")[1]
    .split(":")
    .map((num) => parseInt(num));

  const convertedDate = new Date(
    Date.UTC(date[2], date[1] - 1, date[0], hours[0], hours[1], hours[2])
  );
  return convertedDate;
}
var localDate = getDateFromUTC('22-12-2020 03:44:09 UTC')
console.log(localDate.toString());

Althought, I am not sure why you have a date in string in first place.

Nikhil Patil
  • 2,480
  • 1
  • 7
  • 20
0

Input date is not standard ISO 8601 date format YYYY-MM-DDTHH:mm:ss.sssZ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString

So, you need to parse it first. Here is what I think you can get with the help of moment.js.

function getDateFromUTC(dateString) {
  const parts = dateString.split(' ');
  parts.pop();
  dateString = parts.join(' ');
  const d = moment.tz(
    dateString,
    'DD-MM-YYYY hh:mm:ss',
    'UTC'
  ); 
  return d.toDate().toString();
}

console.log(getDateFromUTC('22-12-2020 03:44:09 UTC'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.31/moment-timezone-with-data.js"></script>

It returns Tue Dec 22 2020, 09:14:09 GMT+0530 (India Standard Time)

Nishant
  • 54,584
  • 13
  • 112
  • 127
0

Browsers will automatically convert to Coordinated Universal Time (UTC) format automatically. You shouldn't need to do any date conversion.

Your back-end does not appear to be returning the correct UTC format according to ISO 8601 standard (UTC Dates end in 'Z').

The correct format for UTC is

[yyyy]-[MM]-[dd]T[HH]:[mm]:[ss].[sss]Z

For example:

2020-12-22T03:44:09.000Z

Michael Kang
  • 52,003
  • 16
  • 103
  • 135
0

There is an issue a month is added I'm not sure why

function getDateFromUTC(dateString) {
  //console.log(mydate);
  var medate = dateString;
  var day = dateString.substring(0, dateString.indexOf('-'));
  dateString = dateString.replace('-', '=')
  var month = dateString.substring(3, dateString.indexOf('-'))
  console.log(month)
  dateString = dateString.replace('-', '=')
  var year = dateString.substring(6, dateString.indexOf(' '))
  dateString = dateString.replace(' ', '=')
  var hour = dateString.substring(11, dateString.indexOf(':'))
  dateString = dateString.replace(':', '=')
  var minute = dateString.substring(14, dateString.indexOf(':'))
  dateString = dateString.replace(':', '=')
  var second = dateString.substring(17, dateString.indexOf(' '))
  medate = year+'-'+month+'-'+day+'T'+hour+':'+minute+':'+second;
  //let utcDate = new Date(year+month+day+'T'+hour+':'+minute+':'+second);
  let utcDate = new Date(medate)
  var mydate = new Date(Date.UTC(
    parseInt(year), 
    parseInt(month)-1, 
    parseInt(day), 
    parseInt(hour), 
    parseInt(minute), 
    parseInt(second),
    0
  ));
  //Apparently one month is added. I'm not sure why
  console.log(mydate)
  console.log(utcDate)
  
}
getDateFromUTC("22-12-2020 03:44:09 UTC");
Steve Nginyo
  • 303
  • 3
  • 12