Stefano Maglione
Stefano Maglione

Reputation: 4150

Formatting date javascript

I'm using var dateString= new Date(parseInt(dateStringUnix)); and I obtain a string as Sun Jun 10 2012 16:40:16 GMT+0200 (ora legale Europa occidentale).

The question is: how can I remove string part GMT+0200 (ora legale Europa occidentale)?

Upvotes: 1

Views: 90

Answers (3)

Fannon
Fannon

Reputation: 423

This is my current favorite, because it's both flexible and modular. It's a collection of (at least) three simple functions:

/**
 * Returns an array with date / time information
 * Starts with year at index 0 up to index 6 for milliseconds
 * 
 * @param {Date} date   date object. If falsy, will take current time.
 * @returns {[]}
 */
getDateArray = function(date) {
    date = date || new Date();
    return [
        date.getFullYear(),
        exports.pad(date.getMonth()+1, 2),
        exports.pad(date.getDate(), 2),
        exports.pad(date.getHours(), 2),
        exports.pad(date.getMinutes(), 2),
        exports.pad(date.getSeconds(), 2),
        exports.pad(date.getMilliseconds(), 2)
    ];
};

Here's the pad function:

 /**
 * Pad a number with n digits
 *
 * @param {number} number   number to pad
 * @param {number} digits   number of total digits
 * @returns {string}
 */
exports.pad = function pad(number, digits) {
    return new Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
};

Finally I can either build my date string by hand, or use a simple functions to do it for me:

/**
 * Returns nicely formatted date-time
 * @example 2015-02-10 16:01:12
 *
 * @param {object} date
 * @returns {string}
 */
exports.niceDate = function(date) {
    var d = exports.getDateArray(date);
    return d[0] + '-' + d[1] + '-' + d[2] + ' ' + d[3] + ':' + d[4] + ':' + d[5];
};

/**
 * Returns a formatted date-time, optimized for machines
 * @example 2015-02-10_16-00-08
 *
 * @param {object} date
 * @returns {string}
 */
exports.roboDate = function(date) {
    var d = exports.getDateArray(date);
    return d[0] + '-' + d[1] + '-' + d[2] + '_' + d[3] + '-' + d[4] + '-' + d[5];
};

Upvotes: 0

saurshaz
saurshaz

Reputation: 509

Go for a simple but powerful library like moment.js . May not be needed if it is a small functionality in your project, but it is eventually a swiss army knife for date and related things

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

Like this:

dateString = dateString.toString().replace(/ GMT.*/,"");

The above just replaces space before GMT, and everything after GMT including GMT with empyt String.

I've used .toString() to convert Object to String so that .replace() can be used.

Upvotes: 1

Related Questions