[javascript] Current time formatting with Javascript

I want to get current time in a specific format with javascript.

With the function below and calling it will give me Fri Feb 01 2013 13:56:40 GMT+1300 (New Zealand Daylight Time) but I want to format it like Friday 2:00pm 1 Feb 2013

var d = new Date();
var x = document.getElementById("time");
x.innerHTML = d;

Of course, code above doesn't have any formatting logic but I have not come across with any "working" formatters yet.

This question is related to javascript date time format

The answer is


You may want to try

var d = new Date();
d.toLocaleString();       // -> "2/1/2013 7:37:08 AM"
d.toLocaleDateString();   // -> "2/1/2013"
d.toLocaleTimeString();  // -> "7:38:05 AM"

Documentation


2017 update: use toLocaleDateString and toLocaleTimeString to format dates and times. The first parameter passed to these methods is a locale value, such as en-us. The second parameter, where present, specifies formatting options, such as the long form for the weekday.

_x000D_
_x000D_
let date = new Date();  _x000D_
let options = {  _x000D_
    weekday: "long", year: "numeric", month: "short",  _x000D_
    day: "numeric", hour: "2-digit", minute: "2-digit"  _x000D_
};  _x000D_
_x000D_
console.log(date.toLocaleTimeString("en-us", options)); 
_x000D_
_x000D_
_x000D_

Output : Wednesday, Oct 25, 2017, 8:19 PM

Please refer below link for more details.

Date and Time Strings (JavaScript)


function startTime() {
    var today = new Date(),
        h = checkTime(((today.getHours() + 11) % 12 + 1)),
        m = checkTime(today.getMinutes()),
        s = checkTime(today.getSeconds());
    document.getElementById('demo').innerHTML = h + ":" + m + ":" + s;
    t = setTimeout(function () {
        startTime()
    }, 500);
}
startTime();

})();

05:12:00


function formatTime(date){

  d = new Date(date);
  var h=d.getHours(),m=d.getMinutes(),l="AM";
  if(h > 12){
    h = h - 12;
  }
  if(h < 10){
    h = '0'+h;
  }
  if(m < 10){
    m = '0'+m;
  }
  if(d.getHours() >= 12){
    l="PM"
  }else{
    l="AM"
  }

  return h+':'+m+' '+l;

}

Usage & result:

var formattedTime=formatTime(new Date('2020 15:00'));
// Output: "03:00 PM"

To work with the base Date class you can look at MDN for its methods (instead of W3Schools due to this reason). There you can find a good description about every method useful to access each single date/time component and informations relative to whether a method is deprecated or not.

Otherwise you can look at Moment.js that is a good library to use for date and time processing. You can use it to manipulate date and time (such as parsing, formatting, i18n, etc.).


There are many great libraries out there, for those interested

There really shouldn't be a need these days to invent your own formatting specifiers.


_x000D_
_x000D_
d = Date.now();_x000D_
d = new Date(d);_x000D_
d = (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear()+' '+(d.getHours() > 12 ? d.getHours() - 12 : d.getHours())+':'+d.getMinutes()+' '+(d.getHours() >= 12 ? "PM" : "AM");_x000D_
_x000D_
console.log(d);
_x000D_
_x000D_
_x000D_


Look at the internals of the Date class and you will see that you can extract all the bits (date, month, year, hour, etc).

http://www.w3schools.com/jsref/jsref_obj_date.asp

For something like Fri 23:00 1 Feb 2013 the code is like:

_x000D_
_x000D_
date = new Date();_x000D_
_x000D_
weekdayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];_x000D_
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];_x000D_
var dateString = weekdayNames[date.getDay()] + " " _x000D_
    + date.getHours() + ":" + ("00" + date.getMinutes()).slice(-2) + " " _x000D_
    + date.getDate() + " " + monthNames[date.getMonth()] + " " + date.getFullYear();_x000D_
_x000D_
console.log(dateString);
_x000D_
_x000D_
_x000D_

**** Modified 2019-05-29 to keep 3 downvoters happy


Using Moment.

I can't recommend the use of Moment enough. If you are able to use third-party libraries, I highly recommend doing so. Beyond just formatting, it deals with timezones, parsing, durations and time travel extremely well and will pay dividends in simplicity and time (at the small expense of size, abstraction and performance).

Usage

You wanted something that looked like this:

Friday 2:00pm 1 Feb 2013

Well, with Moment all you need you to do is this:

import Moment from "moment";

Moment().format( "dddd h:mma D MMM YYYY" ); //=> "Wednesday 9:20am 9 Dec 2020"

And if you wanted to match that exact date and time, all you would need to do is this:

import Moment from "moment";

Moment( "2013-2-1 14:00:00" ).format( "dddd h:mma D MMM YYYY" ) ); //=> "Friday 2:00pm 1 Feb 2013"

There's a myriad of other formatting options that can be found here.

Install

Go to their home page to see more detailed instructions, but if you're using npm or yarn it's as simple as:

npm install moment --save

or

yarn add moment

For this true mysql style use this function below: 2019/02/28 15:33:12

  • If you click the
  • 'Run code snippet' button below
  • It will show your an simple realtime digital clock example The demo will appear below the code snippet.

_x000D_
_x000D_
function getDateTime() {_x000D_
        var now     = new Date(); _x000D_
        var year    = now.getFullYear();_x000D_
        var month   = now.getMonth()+1; _x000D_
        var day     = now.getDate();_x000D_
        var hour    = now.getHours();_x000D_
        var minute  = now.getMinutes();_x000D_
        var second  = now.getSeconds(); _x000D_
        if(month.toString().length == 1) {_x000D_
             month = '0'+month;_x000D_
        }_x000D_
        if(day.toString().length == 1) {_x000D_
             day = '0'+day;_x000D_
        }   _x000D_
        if(hour.toString().length == 1) {_x000D_
             hour = '0'+hour;_x000D_
        }_x000D_
        if(minute.toString().length == 1) {_x000D_
             minute = '0'+minute;_x000D_
        }_x000D_
        if(second.toString().length == 1) {_x000D_
             second = '0'+second;_x000D_
        }   _x000D_
        var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;   _x000D_
         return dateTime;_x000D_
    }_x000D_
_x000D_
    // example usage: realtime clock_x000D_
    setInterval(function(){_x000D_
        currentTime = getDateTime();_x000D_
        document.getElementById("digital-clock").innerHTML = currentTime;_x000D_
    }, 1000);
_x000D_
<div id="digital-clock"></div>
_x000D_
_x000D_
_x000D_


2.39KB minified. One file. https://github.com/rhroyston/clock-js

Current Time is

var str = clock.month;
var m = str.charAt(0).toUpperCase() + str.slice(1,3); //gets you abbreviated month
clock.weekday + ' ' + clock.time + ' ' + clock.day + ' ' + m + ' ' + clock.year; //"tuesday 5:50 PM 3 May 2016"

_x000D_
_x000D_
let date = new Date();_x000D_
let time = date.format("hh:ss")
_x000D_
_x000D_
_x000D_


ISO8601 (eg: HH:MM:SS , 07:55:55 , or 18:50:30) on chrome :

new Date(Date.now()).toTimeString().substr(0,8);

on edge :

new Date(Date.now()).toLocaleTimeString();


You can use my port of strftime:

/* Port of strftime(). Compatibility notes:
 *
 * %c - formatted string is slightly different
 * %D - not implemented (use "%m/%d/%y" or "%d/%m/%y")
 * %e - space is not added
 * %E - not implemented
 * %h - not implemented (use "%b")
 * %k - space is not added
 * %n - not implemented (use "\n")
 * %O - not implemented
 * %r - not implemented (use "%I:%M:%S %p")
 * %R - not implemented (use "%H:%M")
 * %t - not implemented (use "\t")
 * %T - not implemented (use "%H:%M:%S")
 * %U - not implemented
 * %W - not implemented
 * %+ - not implemented
 * %% - not implemented (use "%")
 *
 * strftime() reference:
 * http://man7.org/linux/man-pages/man3/strftime.3.html
 *
 * Day of year (%j) code based on Joe Orost's answer:
 * http://stackoverflow.com/questions/8619879/javascript-calculate-the-day-of-the-year-1-366
 *
 * Week number (%V) code based on Taco van den Broek's prototype:
 * http://techblog.procurios.nl/k/news/view/33796/14863/calculate-iso-8601-week-and-year-in-javascript.html
 */
function strftime(sFormat, date) {
  if (!(date instanceof Date)) date = new Date();
  var nDay = date.getDay(),
    nDate = date.getDate(),
    nMonth = date.getMonth(),
    nYear = date.getFullYear(),
    nHour = date.getHours(),
    aDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    aMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    aDayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
    isLeapYear = function() {
      if ((nYear&3)!==0) return false;
      return nYear%100!==0 || nYear%400===0;
    },
    getThursday = function() {
      var target = new Date(date);
      target.setDate(nDate - ((nDay+6)%7) + 3);
      return target;
    },
    zeroPad = function(nNum, nPad) {
      return ('' + (Math.pow(10, nPad) + nNum)).slice(1);
    };
  return sFormat.replace(/%[a-z]/gi, function(sMatch) {
    return {
      '%a': aDays[nDay].slice(0,3),
      '%A': aDays[nDay],
      '%b': aMonths[nMonth].slice(0,3),
      '%B': aMonths[nMonth],
      '%c': date.toUTCString(),
      '%C': Math.floor(nYear/100),
      '%d': zeroPad(nDate, 2),
      '%e': nDate,
      '%F': date.toISOString().slice(0,10),
      '%G': getThursday().getFullYear(),
      '%g': ('' + getThursday().getFullYear()).slice(2),
      '%H': zeroPad(nHour, 2),
      '%I': zeroPad((nHour+11)%12 + 1, 2),
      '%j': zeroPad(aDayCount[nMonth] + nDate + ((nMonth>1 && isLeapYear()) ? 1 : 0), 3),
      '%k': '' + nHour,
      '%l': (nHour+11)%12 + 1,
      '%m': zeroPad(nMonth + 1, 2),
      '%M': zeroPad(date.getMinutes(), 2),
      '%p': (nHour<12) ? 'AM' : 'PM',
      '%P': (nHour<12) ? 'am' : 'pm',
      '%s': Math.round(date.getTime()/1000),
      '%S': zeroPad(date.getSeconds(), 2),
      '%u': nDay || 7,
      '%V': (function() {
              var target = getThursday(),
                n1stThu = target.valueOf();
              target.setMonth(0, 1);
              var nJan1 = target.getDay();
              if (nJan1!==4) target.setMonth(0, 1 + ((4-nJan1)+7)%7);
              return zeroPad(1 + Math.ceil((n1stThu-target)/604800000), 2);
            })(),
      '%w': '' + nDay,
      '%x': date.toLocaleDateString(),
      '%X': date.toLocaleTimeString(),
      '%y': ('' + nYear).slice(2),
      '%Y': nYear,
      '%z': date.toTimeString().replace(/.+GMT([+-]\d+).+/, '$1'),
      '%Z': date.toTimeString().replace(/.+\((.+?)\)$/, '$1')
    }[sMatch] || sMatch;
  });
}

Sample usage:

// Returns "Thursday 4:45pm 15 Sep 2016"
strftime('%A %l:%M%P %e %b %Y');

// You can optionally pass it a Date object
// Returns "Friday 2:00pm 1 Feb 2013"
strftime('%A %l:%M%P %e %b %Y', new Date('Feb 1, 2013 2:00 PM'));

The latest code is available here: https://github.com/thdoan/strftime


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object

Examples related to format

Brackets.io: Is there a way to auto indent / format <html> Oracle SQL - DATE greater than statement What does this format means T00:00:00.000Z? How to format date in angularjs How do I change data-type of pandas data frame to string with a defined format? How to pad a string to a fixed length with spaces in Python? How to format current time using a yyyyMMddHHmmss format? java.util.Date format SSSSSS: if not microseconds what are the last 3 digits? Formatting a double to two decimal places How enable auto-format code for Intellij IDEA?