Get exact day from date string in Javascript
Asked Answered
A

5

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.

Alligator answered 11/6, 2013 at 6:52 Comment(0)
S
7

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

var final_date = myDate.getDate()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear();
Submultiple answered 11/6, 2013 at 6:56 Comment(0)
P
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.

Peachy answered 11/6, 2013 at 6:58 Comment(1)
You noted, that OP wants the date as dd-mm-yyyy?Submultiple
K
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.

Kafka answered 11/6, 2013 at 6:59 Comment(0)
S
0

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

Steradian answered 11/6, 2013 at 6:56 Comment(0)
C
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")
Crampton answered 31/1, 2023 at 17:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.