-1

I have a little javascript file which I need to get the time of different timezone. I am only able to get the date but not the time.

let today = new Date();
let time = today.getTime();
let us = new Intl.DateTimeFormat('en-US').format(time);
let sv = new Intl.DateTimeFormat('sv').format(time);

console.log(us)
console.log(sv)

result in the console

2/25/2021
2021-02-25
evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
coderboy
  • 741
  • 2
  • 17
  • May you need to add the options object? `new Intl.DateTimeFormat('en-US', { timeStyle: 'short' })`? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat – evolutionxbox Feb 24 '21 at 23:07
  • I'm a little confused. `sv` is not a timezone. The DateTimeFormat is not for timezones, but for formatting. – evolutionxbox Feb 24 '21 at 23:10
  • "not working" is not a description of your problem or your expected results. – StackSlave Feb 24 '21 at 23:52

2 Answers2

0

You can specify the date and time format using the "timeStyle" and "dateStyle" options. These can be full, long, medium, and short.

let us = Intl.DateTimeFormat('en-US', { dateStyle: 'full', timeStyle: 'long' }).format(time));

The above code will produce:

"Weekday, day Month Year at hh:mm:ss GMT+X"
occhietto
  • 15
  • 5
BiOS
  • 2,282
  • 3
  • 10
  • 24
  • 1
    The strange this is that the OP asks _"I need to get the time of different timezone"_ - but the code they provided doesn't do that. I agree with your answer, but it doesn't change the timezone. – evolutionxbox Feb 24 '21 at 23:50
  • I see what you mean evolutionxbox. You're right, it's not extremely clear, though I think that obtaining different timezones may have been the final purpose of his script, and coderboy knew how to do that already, and only got stuck with "extracting the time" part. – BiOS Feb 24 '21 at 23:56
0

i was able to solve the problem by using a javascript method called split whic was able to get me only the time part of the result.

const str3 = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' });
ch_time = str3.split(" ")[1];

console.log(ch_time)
coderboy
  • 741
  • 2
  • 17