Php has a date_format() function which can convert the datetime into any custom format. But sadly javascript do not have any such thing. So, we have implemented one for it. Although, there are many wonderful libraries like moment.js to deal with datetime but sometimes we just want simple and lightweight solution. With this function, you can easily get any javascript date format.

(function () {
  // Defining locale
  Date.shortMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  Date.longMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
  Date.shortDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  Date.longDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
  // Defining patterns
  var replaceChars = {
    // Day
    d: function () { var d = this.getDate(); return (d < 10 ? '0' : '') + d },
    D: function () { return Date.shortDays[this.getDay()] },
    j: function () { return this.getDate() },
    l: function () { return Date.longDays[this.getDay()] },
    N: function () { var N = this.getDay(); return (N === 0 ? 7 : N) },
    S: function () { var S = this.getDate(); return (S % 10 === 1 && S !== 11 ? 'st' : (S % 10 === 2 && S !== 12 ? 'nd' : (S % 10 === 3 && S !== 13 ? 'rd' : 'th'))) },
    w: function () { return this.getDay() },
    z: function () { var d = new Date(this.getFullYear(), 0, 1); return Math.ceil((this - d) / 86400000) },
    // Week
    W: function () {
      var target = new Date(this.valueOf())
      var dayNr = (this.getDay() + 6) % 7
      target.setDate(target.getDate() - dayNr + 3)
      var firstThursday = target.valueOf()
      target.setMonth(0, 1)
      if (target.getDay() !== 4) {
        target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7)
      }
      var retVal = 1 + Math.ceil((firstThursday - target) / 604800000)

      return (retVal < 10 ? '0' + retVal : retVal)
    },
    // Month
    F: function () { return Date.longMonths[this.getMonth()] },
    m: function () { var m = this.getMonth(); return (m < 9 ? '0' : '') + (m + 1) },
    M: function () { return Date.shortMonths[this.getMonth()] },
    n: function () { return this.getMonth() + 1 },
    t: function () {
      var year = this.getFullYear()
      var nextMonth = this.getMonth() + 1
      if (nextMonth === 12) {
        year = year++
        nextMonth = 0
      }
      return new Date(year, nextMonth, 0).getDate()
    },
    // Year
    L: function () { var L = this.getFullYear(); return (L % 400 === 0 || (L % 100 !== 0 && L % 4 === 0)) },
    o: function () { var d = new Date(this.valueOf()); d.setDate(d.getDate() - ((this.getDay() + 6) % 7) + 3); return d.getFullYear() },
    Y: function () { return this.getFullYear() },
    y: function () { return ('' + this.getFullYear()).substr(2) },
    // Time
    a: function () { return this.getHours() < 12 ? 'am' : 'pm' },
    A: function () { return this.getHours() < 12 ? 'AM' : 'PM' },
    B: function () { return Math.floor((((this.getUTCHours() + 1) % 24) + this.getUTCMinutes() / 60 + this.getUTCSeconds() / 3600) * 1000 / 24) },
    g: function () { return this.getHours() % 12 || 12 },
    G: function () { return this.getHours() },
    h: function () { var h = this.getHours(); return ((h % 12 || 12) < 10 ? '0' : '') + (h % 12 || 12) },
    H: function () { var H = this.getHours(); return (H < 10 ? '0' : '') + H },
    i: function () { var i = this.getMinutes(); return (i < 10 ? '0' : '') + i },
    s: function () { var s = this.getSeconds(); return (s < 10 ? '0' : '') + s },
    v: function () { var v = this.getMilliseconds(); return (v < 10 ? '00' : (v < 100 ? '0' : '')) + v },
    // Timezone
    e: function () { return Intl.DateTimeFormat().resolvedOptions().timeZone },
    I: function () {
      var DST = null
      for (var i = 0; i < 12; ++i) {
        var d = new Date(this.getFullYear(), i, 1)
        var offset = d.getTimezoneOffset()

        if (DST === null) DST = offset
        else if (offset < DST) { DST = offset; break } else if (offset > DST) break
      }
      return (this.getTimezoneOffset() === DST) | 0
    },
    O: function () { var O = this.getTimezoneOffset(); return (-O < 0 ? '-' : '+') + (Math.abs(O / 60) < 10 ? '0' : '') + Math.floor(Math.abs(O / 60)) + (Math.abs(O % 60) === 0 ? '00' : ((Math.abs(O % 60) < 10 ? '0' : '')) + (Math.abs(O % 60))) },
    P: function () { var P = this.getTimezoneOffset(); return (-P < 0 ? '-' : '+') + (Math.abs(P / 60) < 10 ? '0' : '') + Math.floor(Math.abs(P / 60)) + ':' + (Math.abs(P % 60) === 0 ? '00' : ((Math.abs(P % 60) < 10 ? '0' : '')) + (Math.abs(P % 60))) },
    T: function () { var tz = this.toLocaleTimeString(navigator.language, {timeZoneName: 'short'}).split(' '); return tz[tz.length - 1] },
    Z: function () { return -this.getTimezoneOffset() * 60 },
    // Full Date/Time
    c: function () { return this.format('Y-m-d\\TH:i:sP') },
    r: function () { return this.toString() },
    U: function () { return Math.floor(this.getTime() / 1000) }
  }

  // Simulates PHP's date function
  Date.prototype.format = function (format) {
    var date = this
    return format.replace(/(\\?)(.)/g, function (_, esc, chr) {
      return (esc === '' && replaceChars[chr]) ? replaceChars[chr].call(date) : chr
    })
  }
}).call(this);

function date_format(dateVal, formatVal){
    return dateVal.format(formatVal);
}

    Tweet this to help others

Using JS date_format()

This function expects two parameters – Date and Format string. You may create date using any method which javascript supports like timestamp milliseconds or datetime string. It just requires the date obj.

var dateVal = new Date();
date_format(dateVal, 'd-m-Y');
// Output: 21-12-2020

This can also convert a string in to unix timestamp or datetime javascript format.

Date Format String Table

Format characterDescriptionOutput
Day
dDay of the month, 2 digits with leading zeros01 to 31
DA textual representation of a day, three lettersMon through Sun
jDay of the month without leading zeros1 to 31
l (lowercase L)A full textual representation of the day of the weekSunday through Saturday
NISO-8601 numeric representation of the day of the week1 (for Monday) through 7 (for Sunday)
SEnglish ordinal suffix for the day of the month, 2 charactersstndrd or th. Works well with j
wNumeric representation of the day of the week0 (for Sunday) through 6 (for Saturday)
zThe day of the year (starting from 0)0 through 365
Week
WISO-8601 week number of year, weeks starting on MondayExample: 42 (the 42nd week in the year)
Month
FA full textual representation of a month, such as January or MarchJanuary through December
mNumeric representation of a month, with leading zeros01 through 12
MA short textual representation of a month, three lettersJan through Dec
nNumeric representation of a month, without leading zeros1 through 12
tNumber of days in the given month28 through 31
Year
LWhether it’s a leap year1 if it is a leap year, 0 otherwise.
oISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead.Examples: 1999 or 2003
YA full numeric representation of a year, 4 digitsExamples: 1999 or 2003
yA two digit representation of a yearExamples: 99 or 03
Time
aLowercase Ante meridiem or Post meridiemam or pm
AUppercase Ante meridiem or Post meridiemAM or PM
BSwatch Internet time000 through 999
g12-hour format of an hour without leading zeros1 through 12
G24-hour format of an hour without leading zeros0 through 23
h12-hour format of an hour with leading zeros01 through 12
H24-hour format of an hour with leading zeros00 through 23
iMinutes with leading zeros00 to 59
sSeconds, with leading zeros00 through 59
vMillisecondsExample: 654
Timezone
eTimezone identifierAtlantic/Azorest or Europe/Amsterdam
I (capital i)Whether or not the date is in daylights savings time1 if Daylight Savings Time, 0 otherwise.
O (capital o)Difference to Greenwich time (GMT) in hoursExample: +0200
PDifference to Greenwich time (GMT) with colon between hours and minutesExample: +02:00
TTimezone setting of this machineExamples: EST or MDT
ZTimezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.-43200 through 43200
Full Date/Time
cISO 8601 formatted dateExample: 2017-11-26T15:12:21+00:00
rRFC 2822 formatted dateExample: Thu, 21 Dec 2000 16:01:07 +0200
USeconds since the Unix Epoch (January 1 1970 00:00:00 GMT)Example: 1501804996

You may also like this article –

Examples

Format – YYYY-MM-DD HH-mm-ss
var dateVal = new Date();
date_format(dateVal, 'd-m-Y H:i:s');
Format – Dec 21st, 2020
var dateVal = new Date();
date_format(dateVal, 'M jS, Y');
Format – Today is 21-12-2020
var dateVal = new Date();
date_format(dateVal, '\\T\\o\\d\\a\\y \\i\\s d-m-Y');
Format – Unix Timestamp (milliseconds)
var dateVal = new Date();
date_format(dateVal, 'U') * 1000;
Format – Twitter feed tweet post time

This example will help you in getting the comparison of dates. When somebody posts a tweet on tweeter feed or Facebook post or Instagram photo or comments anywhere, they use to show the time since it was posted. This time could be in seconds, minutes, even weeks or months. Our date_format() function can help in getting that too.

var currentTime = Date.now();
var commentPostTime = new Date('2020-12-22 00:12:43');

var timePassedAfterCommentInSeconds = currentTime - commentPostTime;

Tagged in:

,

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles