[javascript] javascript date to string

Here is what I need to do.

Get Date, convert to string and pass it over to a third party utility. The response from the library will have date in string format as I passed it. So, I need to convert the date to string like 20110506105524 (YYYYMMDDHHMMSS)

function printDate() {
    var temp = new Date();
    var dateStr = temp.getFullYear().toString() + 
                  temp.getMonth().toString() + 
                  temp.getDate().toString() +
                  temp.getHours().toString() + 
                  temp.getMinutes().toString() + 
                  temp.getSeconds().toString();

    debug (dateStr );
}

The problem with above is that for months 1-9, it prints one digit. How can I change it to print exactly 2 digits for month, date ...

This question is related to javascript string date

The answer is


I like Daniel Cerecedo's answer using toJSON() and regex. An even simpler form would be:

var now = new Date();
var regex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).*$/;
var token_array = regex.exec(now.toJSON());
// [ "2017-10-31T02:24:45.868Z", "2017", "10", "31", "02", "24", "45" ]
var myFormat = token_array.slice(1).join('');
// "20171031022445"

Maybe it is easier to convert the Date into the actual integer 20110506105524 and then convert this into a string:

function printDate() {
    var temp = new Date();
    var dateInt =
        ((((temp.getFullYear() * 100 + 
            temp.getMonth() + 1) * 100 + 
           temp.getDate()) * 100 +
          temp.getHours()) * 100 + 
         temp.getMinutes()) * 100 + 
        temp.getSeconds();

    debug ( '' + dateInt );  // convert to String
}

When temp.getFullYear() < 1000 the result will be one (or more) digits shorter.

Caution: this wont work with millisecond precision (i.e. 17 digits) since Number.MAX_SAFE_INTEGER is 9007199254740991 which is only 16 digits.


A little bit simpler using regex and toJSON().

var now = new Date();
var timeRegex = /^.*T(\d{2}):(\d{2}):(\d{2}).*$/
var dateRegex = /^(\d{4})-(\d{2})-(\d{2})T.*$/
var dateData = dateRegex.exec(now.toJSON());
var timeData = timeRegex.exec(now.toJSON());
var myFormat = dateData[1]+dateData[2]+dateData[3]+timeData[1]+timeData[2]+timeData[3]

Which at the time of writing gives you "20151111180924".

The good thing of using toJSON() is that everything comes already padded.


Relying on JQuery Datepicker, but it could be done easily:

var mydate = new Date();
$.datepicker.formatDate('yy-mm-dd', mydate);

use this polyfill https://github.com/UziTech/js-date-format

var d = new Date("1/1/2014 10:00 am");
d.format("DDDD 'the' DS 'of' MMMM YYYY h:mm TT");
//output: Wednesday the 1st of January 2014 10:00 AM

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 string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

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?