简体   繁体   中英

How can I reduce the live date/time string with javascript?

I have made a time/date script but I am unsure how I can reduce the string to display only AEDT. I have seen lots of time/date converters but they all seem to apply to static time. not a live update.

From: SAT NOV 28 2020 14:54:16 GMT+1100 (AUSTRALIAN EASTERN DAYLIGHT TIME)

To: SAT NOV 28 2020 14:54:16 AEDT.

see my code..

<script type="text/javascript">
  function display_c(){
  var refresh=1000; // Refresh rate in milli seconds
  mytime=setTimeout('display_ct()',refresh)
  }

  function display_ct() {
  var x = new Date()
  document.getElementById('ct').innerHTML = x;
  display_c();
   }


<span id='ct'></span>

If you don't want to use an external library, check out toLocateString() with options . Be sure to check the browser compatibility table at the bottom and if you're okay with that.

In your case I'd do something like this (you can always strip out comma with a simple string replace):

 var dateTimeOptions = { weekday: 'short', year: 'numeric', month: 'short', day: '2-digit', hour12: false, hour: 'numeric', minute: 'numeric', second: 'numeric', timeZoneName: 'short' }; function display_c() { var refresh = 1000; // Refresh rate in milli seconds mytime = setTimeout('display_ct()', refresh) } function display_ct() { var x = new Date(); document.getElementById('ct').innerHTML = x.toLocaleString('en', dateTimeOptions); display_c(); } display_c();
 <span id='ct'></span>

If you need more extensive date/time formatting, you can go with a library like momentjs.

The best way to do this is to use the moment.js library ( https://momentjs.com/ ):

<script src="https://momentjs.com/downloads/moment.min.js"></script>

And use it like this:

let x = moment().format('ddd MMM DD YYYY HH:mm:ss ZZ');

which gives

Sat Nov 28 2020 15:23:25 +1100

If you really want the named timezone (eg AEDT), then you'll need the timezone data:

<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>

and you can obtain the timezone like this:

let timezone = moment.tz(moment.tz.guess()).zoneAbbr();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM