0
     <div>
        <strong>Date: </strong>
        ${dateInUtc}
     </div>

This dateInUtc (2021-12-09T15:43:29+01:00) contains the date in UTC format. Need to format it like this 2021-12-09 - 15:43:29.

How do achieve this without using external libraries?

Ramdhas
  • 1,765
  • 1
  • 18
  • 26

2 Answers2

1

Because the required format is close to what you already have you can do this quite simply without having to parse the date in the first place.

const dateInUtc = `2021-12-09T15:43:29+01:00`;

const formattedDate = dateInUtc.replace(`T`, ` - `).split(`+`)[0];

console.log(formattedDate);
phuzi
  • 12,078
  • 3
  • 26
  • 50
  • If we pass the date in another format we can't do that. like: Input: `new Date().toUTCString().replace(`T`, ` - `).split(`+`)[0]` Output: `Fri, 22 Jul 2022 09:21:42 GM - ` – Art Bindu Jul 22 '22 at 09:22
  • @ArtBindu I did prefix the answer with _"Because the required format is close to what you already have"_. If this solution doesn't work for you then check out the duplicate I linked 8o) – phuzi Jul 22 '22 at 09:33
  • Also, you could use `.toISOString()` – phuzi Jul 22 '22 at 09:36
1

If you are using any framework then use Datapipe in that framework.

Example: Datepipe-Angular

If you are not using any framework then use the date format utility function like:

df = (function(d) {
    d = new Date(d);
    return `${d.getFullYear()}-${(d.getMonth()+1).toString().replace(/^[0-9]$/g, '0$&')}-${(d.getDate()).toString().replace(/^[0-9]$/g, '0$&')} - ${(d.getHours()).toString().replace(/^[0-9]$/g, '0$&')}:${(d.getMinutes()).toString().replace(/^[0-9]$/g, '0$&')}:${(d.getSeconds()).toString().replace(/^[0-9]$/g, '0$&')}`;
});
console.log(df(new Date().toUTCString()));

Output:

'2022-07-22 - 14:41:36'

Explanation: This is the objective to get data from the Date object.

    d = new Date(d);
    obj = {
        date: d.getDate(),
        month: d.getMonth(),
        year: d.getFullYear(),
        hour: d.getHours(),
        minute: d.getMinutes(),
        second: d.getSeconds()
    }

I am using regular expression str.replace(/^[0-9]$/g, '0$&') or str.replace(/^[0-9]{1}$/g, '0$&')to add an addition zero if data is a single digit. Like:

'0'.replace(/^[0-9]$/g, '0$&') // '00'
'8'.replace(/^[0-9]$/g, '0$&') // '08'
'12'.replace(/^[0-9]$/g, '0$&') //'12'
Art Bindu
  • 769
  • 4
  • 14
  • Why are you taking a date and formatting it (string) and then parsing it again. Why not just pass the date to `df` – phuzi Jul 22 '22 at 09:39
  • According to the question, pass some dates in UTC format. It's not mandatory ... – Art Bindu Jul 22 '22 at 14:32