-2

I want time and date format like this

UK: 08-08-21 01:27 PM

SL: 08-08-21 05:57 PM

I tried with this. But i does not work properly

this.subscription = timer(0, 60000)
      .pipe(
        map(() => new Date()),
        share()
      )
      .subscribe(time => {

        let day = new Date().getDay();
        let month = new Date().getMonth();
        let year = new Date().getFullYear();
        let SlHour = new Date().getHours();
        let UkHour = new Date().getUTCHours()+ 1;
        let minuts = new Date().getUTCMinutes();

        let SLTime = day + "-" + month + "-" + year + " " + UkHour + ":" + minuts
        let UKTime = day + "-" + month + "-" + year + " " + SlHour + ":" + minuts
     }

Can anyone help me to get like this format

UK: 08-08-21 01:27 PM

SL: 08-08-21 05:57 PM

hanushic
  • 11
  • 5
  • Please define *"does not work properly"* in more specific technical terms. In other words.... What is or isn't working as expected? – charlietfl Aug 08 '21 at 12:35

3 Answers3

0

Trying to format the date seperator -

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Static Template</title>
</head>

<body>
  <div>
    UK:
    <h4 id="app-uk"></h4>
  </div>
  <div>
    SL:
    <h4 id="app-sl"></h4>
  </div>

  <script>
    let now = new Date();

    let formatDateUK = now.toLocaleString("en-UK", {
      dateStyle: "short",
      timeStyle: "short",
      hour12: true
    });

    let formatDateSL = now.toLocaleString("en-SL", {
      dateStyle: "short",
      timeStyle: "short",
      hour12: true
    });

    let displayDateUK = document.querySelector("#app-uk");
    displayDateUK.innerHTML = formatDateUK;

    let displayDateSL = document.querySelector("#app-sl");
    displayDateSL.innerHTML = formatDateSL;
  </script>
</body>

</html>
Momin
  • 3,200
  • 3
  • 30
  • 48
  • For UK in Safari I get 8/9/21, 6:51 AM which might be unexpected given it's 9 August. – RobG Aug 08 '21 at 20:53
-1

I wrote a formatDate function. If ukTime is true, the result will be London time, and if it is false you will get local time. This should work for your purpose.

The UK time is generated using a date-string-date method because adding 1 to the hour can result in invalid times.

Edit: Fixed 00AM to 12AM.

function formatDate(ukTime = false) {
    let dt;
    if (ukTime) dt = new Date(new Date().toLocaleString("en-US", { timeZone: "Europe/London" }));
    else dt = new Date();

    let dayStr = dt.getDate().toString().padStart(2, "0"),
        monthStr = (dt.getMonth() + 1).toString().padStart(2, "0"),
        yearStr = dt.getYear().toString().substring(1, 3);
    let hour = dt.getHours() > 12 ? dt.getHours() - 12 : (dt.getHours() == 0 ? 12 : dt.getHours());
    
    return `${dayStr}-${monthStr}-${yearStr} ${hour.toString().padStart(2, "0")}:${dt.getMinutes().toString().padStart(2, "0")} ${dt.getHours() >= 12 ? "PM" : "AM"}`;
}


console.log(formatDate(true))
console.log(formatDate(false))
addeo
  • 34
  • 4
  • Thank you. But i want time should update every minutes . – hanushic Aug 08 '21 at 13:30
  • If you want to update, make a function that runs often and updates the time using formatDate. – addeo Aug 08 '21 at 13:39
  • Consider `let hour = dt.getHours() % 12 || 12`. – RobG Aug 08 '21 at 22:10
  • The strategy of creating a string then parsing it to create a timezone–shifted date as in `dt = new Date(new Date().toLocaleString("en-US", { timeZone: "Europe/London" }));` is flawed as it relies on the built–in parser parsing the output of *toLocaleSring* when it's not required to do so (and won't in many cases) and it may generate a time that either doesn't exist locally or exists twice during DST transitions. Better to use [*formatToParts*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts) with an appropriate IANA location. – RobG Aug 08 '21 at 23:49
  • Thanks for letting me know, that’d probably work better. – addeo Aug 10 '21 at 17:13
-1

There are a number of errors in the code:

let day = new Date().getDay();

returns the day number (Sunday = 0, Monday = 1, etc.) not the date

let month = new Date().getMonth();

returns the month index where Jan = 0, Feb = 1, etc. so you need to add 1 to get the calendar month number.

let UkHour = new Date().getUTCHours()+ 1;

This assumes that the UK time is always UTC +1, which it isn't and also will return 24 when the hour should be 0.

The code also creates a new Date object each time, which is inefficient. To get the date and time in a particular location, use the timeZone option of the Intl.DateTimeFormat constructor, which is also available through toLocaleString.

Since localised formats of dates and times are not standardised, you might use the formatToParts method that returns the parts of a date as an array of objects, where each part has a name and value. Then you can reliably format the parts, e.g. assuming "SL" means "standard local":

// Format date as DD/MM/YY h:mm AP
function formatDate(date = new Date(), location) {
  // Standard options
  let opts = {
    day: '2-digit',
    month: '2-digit',
    year: '2-digit',
    hour: 'numeric',
    minute: '2-digit',
    second: '2-digit',
    hour12: true
  };
  // Add timezone if supplied
  if (location) {
    opts.timeZone = location;
  }
  // Create a formatter  
  let f = new Intl.DateTimeFormat('en', opts);
  // Get the parts
  let {year, month, day, hour, minute, dayPeriod} = f.formatToParts(date).reduce(
    (acc, part) => {
      acc[part.type] = part.value;
      return acc
    }, {}
  );
  // Return formatted string
  return `${day}-${month}-${year} ${hour}:${minute} ${dayPeriod.toUpperCase()}`;
}

console.log('UK (London): ' + formatDate(new Date(), 'Europe/London'));
console.log('Vladivostok: ' + formatDate(new Date(), 'Asia/Vladivostok'))
console.log('Local      : ' + formatDate());

The format DD-MM-YY is ambiguous, not least due to the US penchant for M/D/Y but also because many places use Y-M-D, so 01-02-03 might be interpreted 3 different ways. Better to use the short month name to avoid that, e.g. 09-Aug-21. Four digit year would also be better.

RobG
  • 142,382
  • 31
  • 172
  • 209