Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Convert dd/mm/yyyy or d/m/yyyy, etc to yyyymmdd in Javascript

Convert dd/mm/yyyy or d/m/yyyy, etc to yyyymmdd in Javascript

Problem

im trying to convert a date format into a new format in this example is d/m/Y to Ymd, this is how i do it in PHP with DateTime::createFromFormat() is there a similer function in javascript to do this?

    // 12/04/2012 work
    // 12/4/2012 work
    // 4/4/2012 work
    // 04/4/2012 work
    // 42/24/1234 not work

$date = DateTime::createFromFormat('d/m/Y', '12/04/2012');
$train_date = $date->format('Ymd'); change the format to // 20120412

in short how can i do this in javascript or nodejs?

Problem courtesy of: user1447162

Solution

It's nice to use external libraries since node.js has a philosophy of minimal core library. Let's have a look at moment.js.

var moment = require('moment');
var date = moment('12/04/2012', 'DD/MM/YYYY');
var train_date = date.format('YYYYMMDD');
console.log(train_date);// 20120412
Solution courtesy of: smagch

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Convert dd/mm/yyyy or d/m/yyyy, etc to yyyymmdd in Javascript

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×