Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a date string in javascript

Hello every i have date field of type string with iso format like this: const date = "2017-06-10T16:08:00: i want somehow to edit the string in the following format like this: 10-06-2017 but i'm struggling in achieving this. I cut the substring after the "T" character

like image 397
user7334203 Avatar asked Jun 12 '17 06:06

user7334203


3 Answers

It can be achieved without moment.js, but I suggest you use it

var date = new Date("2017-06-10T16:08:00");

var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();

if (day < 10) {
  day = '0' + day;
}
if (month < 10) {
  month = '0' + month;
}

var formattedDate = day + '-' + month + '-' + year
like image 200
Ivan Mladenov Avatar answered Oct 10 '22 21:10

Ivan Mladenov


Use Moment.js and the .format function.

moment('2017-06-10T16:08:00').format('MM/DD/YYYY');

Will output

06/10/2017

Beside the format function Moment.js will enrich you will alot more useful functions.

like image 41
daan.desmedt Avatar answered Oct 10 '22 22:10

daan.desmedt


If the date string is always in ISO format, you can also use regex to reformat without other library:

date.replace(/(\d{4})\-(\d{2})\-(\d{2}).*/, '$3-$2-$1')
like image 20
micebrain Avatar answered Oct 10 '22 21:10

micebrain