简体   繁体   中英

Format date and time in refresh

I want to use the following script to refresh the time every second. Works fine, but I want it to output the format like this:

October 06 - 13:38:04.

How do you do that?

 var timestamp = '<?=time();?>'; function updateTime(){ const firstOption = {month: 'long', day: 'numeric'}; const secondOptions = { hour: 'numeric', minute: 'numeric', second: 'numeric' }; $('#time').html(new Date(timestamp).toLocaleDateString("en-NL", firstOption) + " - " + new Date(timestamp).toLocaleTimeString("en-NL", secondOptions)); timestamp++; } $(function(){ setInterval(updateTime, 1000); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p id="time"></p>

Try this:

 const firstOption = {month: 'long', day: 'numeric'};
 const secondOptions = { hour: 'numeric', minute: 'numeric', second: 'numeric' };
$('#time').html(new Date(timestamp).toLocaleDateString("en-NL", firstOption) + " - " + new Date(timestamp).toLocaleTimeString("en-NL", secondOptions));

Read more about it here.

Simple function for formating your date.

function dateToString(/* add timestamp parameter if you want */) {
  
  var d = new Date(/* timestamp parameter here */);

  var months = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July',
    'August',
    'October',
    'November',
    'December',
  ]
  
  var month = months[d.getMonth() - 1];
  var date = (d.getDate() < 10) ? "0" + d.getDate() : d.getDate();
  var hours = d.getHours(),
      minutes = d.getMinutes(),
      seconds = d.getSeconds();
  
  var time = (hours < 10 ? "0" + hours : hours) + ':' + (minutes < 10 ? "0" + 
minutes : minutes) + ':' + (seconds < 10 ? "0" + seconds : seconds);
  
  return month + ' ' + date + ' - ' + time;
}

dateToString(/* pass timestamp argument here */);

Afaik PHP's time function return a unix timestamp and you're looking for an ES5 solution. This might help you.

 const datetime = 1601984483; var padStart = function(str, length) { while (str.toString().length < length) str = "0" + str; return str; } var format = function (timestamp) { var date = new Date(); var d = { M: date.toLocaleString('default', { month: 'long' }), d: padStart(date.getDate(), 2), h: padStart(date.getHours(), 2), m: padStart(date.getMinutes(), 2), s: padStart(date.getSeconds(), 2) }; return [[dM, dd].join(' '), [dh, dm, ds].join(':')].join(' '); } console.log(format(datetime));

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