5

I have checked this SO post: Where can I find documentation on formatting a date in JavaScript?

Also I have looked into http://home.clara.net/shotover/datetest.htm

My string is: Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)

And I want to convert it to dd-mm-yyyy format.

I tried using:

var dateString = 'Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)';
var myDate = new Date(dateString);
var final_date = myDate.getDay()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();

But it gives me the result as: 1-6-2013

The getDay() value is the index of day in a week.
For Instance, If my dateString is Thu Jun 20 2013 05:30:00 GMT+0530 (India Standard Time)
it gives output as 4-6-2013

How can I get the proper value of Day?

P.S: I tried using .toLocaleString() and creating new date object from it. But it gives the same result.

Community
  • 1
  • 1
Prasad Jadhav
  • 5,090
  • 16
  • 62
  • 80

5 Answers5

7

To get the day of the month use getDate():

var final_date = myDate.getDate()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();
Sirko
  • 72,589
  • 19
  • 149
  • 183
4

W3 schools suggests just building your days of the week array and using it:

var d=new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

var n = weekday[d.getDay()];

Not super elegant, but usable.

mike
  • 22,931
  • 31
  • 77
  • 100
4
var dateString = 'Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)';
var myDate = new Date(dateString);
var final_date = myDate.getDate()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();

Replace getDay() with getDate().

The above will return the local date for each date part, use the UTC variants if you need the universal time.

Sparko
  • 735
  • 6
  • 15
0

I think you will have to take an Array of the days & utilize it using the received index from the getDay() method.

Adam Lear
  • 38,111
  • 12
  • 81
  • 101
powercoder23
  • 1,404
  • 1
  • 13
  • 22
0

To get required format with given date will achieve with moment.js. a one liner solution is

import moment from "moment";

const date = new Date();
const finalDate = moment(date).format("DD-MM-YYYY")
DineshMsd
  • 72
  • 1
  • 9