Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get Only Day Name or Number in a Week in JavaScript Date()

I am using following code snippets to get the First and last Day of month which working fine but what I need is getting only the Name string like "Fri", "Wed", "Sun" and the code is returning a long Date format as:

Fri Oct 31 2014 00:00:00 GMT-0700 (Pacific Daylight Time)

var today = new Date();
var lastOfMonth = new Date(today.getFullYear(),today.getMonth()+1, 0);

var today = new Date();
var firstOfMonth = new Date(today.getFullYear(),today.getMonth(), 1);

Can you please let me know how I can get ONLY the Name or Number of the day in a week (using getDay()) of the First day?

like image 352
Suffii Avatar asked Oct 16 '14 07:10

Suffii


People also ask

How do you get the name of the day of the week in JavaScript?

You could use the Date. getDay() method, which returns 0 for sunday, up to 6 for saturday. So, you could simply create an array with the name for the day names: var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; var d = new Date(dateString); var dayName = days[d.

How do I get the current week number in JavaScript?

Add the number of days to the current weekday using getDay() and divide it by 7. We will get the current week's number.

What is getDate () in JavaScript?

The getDate() method returns the day of the month for the specified date according to local time.

What is the first day of the week JavaScript?

Generally, the day of the week starts from 0 (Sunday) and ends with 6 (Saturday). By default, the first day of the week is culture specific.


3 Answers

Use haven't use getDay

today.getDay();

first of month

 firstOfMonth.getDay();

last of month

 lastOfMonth.getDay();

or if u want to get dayname use

var days = ['Sun','Mon','Tues','Wed','Thrus','Fri','Sat'];
//First of month
days[firstOfMonth.getDay()];
//last of month
days[lastOfMonth.getDay()];
like image 91
Naveen Singh raghuvanshi Avatar answered Oct 08 '22 04:10

Naveen Singh raghuvanshi


You can define arrays

var Months = ['Jan','Feb'....];
var Days = ['Sun','Mon','Tues','Wednes','Thurs','Fri','Sat'];

var firstOfMonth = new Date(today.getFullYear(),Months[today.getMonth()], 1);

var Day = Days[today.getDay()];
like image 38
Fatima Zohra Avatar answered Oct 08 '22 05:10

Fatima Zohra


Use

lastOfMonth.getDay()

to get the day number.

You can use an array like

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";

to get the written day with

var writtenDay = weekday[lastOfMonth.getDay()];
like image 21
Barry Avatar answered Oct 08 '22 05:10

Barry