Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting the date time with Javascript

I have a date/time string like 2012-01-13 04:37:20 but I want to convert it to dd-mm-yyyy hh:mm, how can i do this?

I am using the following code but it throws an exception.

var now = "2012-01-13 04:37:20";
var dd = now.toLocaleDateString() + " " + now.toLocaleTimeString();
alert(dd);
like image 801
vipin katiyar Avatar asked Jan 13 '12 07:01

vipin katiyar


People also ask

What is JavaScript date format?

The preferred Javascript date formats are: Dates Only — YYYY-MM-DD. Dates With Times — YYYY-MM-DDTHH:MM:SSZ.

What date format is DD MMM YYYY JavaScript?

There is no native format in JavaScript for” dd-mmm-yyyy”. To get the date format “dd-mmm-yyyy”, we are going to use regular expression in JavaScript. The regular expression in JavaScript is used to find the pattern in a string. So we are going to find the “dd-mmm-yyyy” pattern in the string using match() method.


2 Answers

A small but effective function, as follows:

var formatTime = function(time, format){
    time = typeof time == 'number' ? new Date(time) : time;
    format = format || 'yyyy-mm-dd hh:MM:ss';
    var add0 = function(t){ return t < 10 ? '0' + t : t; };
    var year = time.getFullYear();
    var month = time.getMonth() + 1; // 0 indexed
    var date = time.getDate();
    var hours = time.getHours();
    var minutes = time.getMinutes();
    var seconds = time.getSeconds();
    var replaceMent = {
        'yyyy': year,
        'mm': add0(month),
        'm': month,
        'dd': add0(date),
        'd': date,
        'hh': add0(hours),
        'h': hours,
        'MM': add0(minutes),
        'M': minutes,
        'ss': add0(seconds),
        's': seconds
    }
    for(var key in replaceMent){
        format = format.replace(key, replaceMent[key]);
    }
    return format;
}

Example usage:

// As Date Input
formatTime(new Date()); // 2020-12-10 16:29:32
// As Date Input
formatTime(new Date(),"yyyy-mm-dd"); // 2020-12-10
// OR
formatTime(new Date(),"hh:MM:ss"); // 16:29:32
// As Time Input
formatTime(new Date().getTime()); // 2020-12-10 16:29:32
// OR
formatTime(1607606809630); // 2020-12-10 16:29:32
// OR
formatTime(1607606809630,"yyyy-mm-dd"); // 2020-12-10
// OR
formatTime(1607606809630,"hh:MM:ss"); // 16:29:32
like image 107
user3117708 Avatar answered Oct 05 '22 11:10

user3117708


If you don't need all the features that a library like Moment.js provides, then you can use my port of strftime. It's lightweight (1.35 KB vs. 57.9 KB minified compared to Moment.js 2.15.0) and provides most of the functionality 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() {
      return (nYear%4===0 && 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 "15-09-2016 16:20"
strftime('%d-%m-%Y %H:%M');

// You can optionally pass it a Date object
// Returns "01-01-2016 21:30"
strftime('%d-%m-%Y %H:%M', new Date('Jan 1, 2016 9:30 PM'));

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

like image 45
thdoan Avatar answered Oct 05 '22 12:10

thdoan