Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Date() object with specific time

I want to get week Start Date of a week. I am able to get the date, its just that the date returned has time wrt to the current system time. For example, if its 19:20 hours right now, I am getting the week start date as Date {Mon Mar 26 2012 19:20:16 GMT+0530 (IST)}

For accurate calculations, I need the time to be 00:00:00 GMT.

How can I achieve that?

My current code looks like this:

var tDate = new Date();
var wDate = new Date();

this.chosenDayIndex = this.currentDayIndex = tDate.getDay();

if (this.currentDate == '') {

    this.currentDate = new Date();  
    var today = formatDate(tDate);
    var diff = tDate.getDate() - this.currentDayIndex + (this.currentDayIndex == 0 ? -6:1);

    this.weekStartDate = this.weekMonDate = new Date(wDate.setDate(diff));
    this.weekEndDate = new Date(this.weekStartDate.getFullYear(),this.weekStartDate.getMonth(), this.weekStartDate.getDate()+6);
    this.weekMonday = formatDate(this.weekMonDate);             

}

this.weekStartDate is currently handing out the false start date with the current timestamp.

like image 665
amit Avatar asked Dec 17 '22 02:12

amit


2 Answers

You can set the date to the start of the week with this:

var d = new Date();
d.setDate(d.getDate() - d.getDay());

Then use .setHours(0), .setMinutes(0), etc. to clear out the time.

like image 127
Pointy Avatar answered Jan 09 '23 00:01

Pointy


if you start your week on Monday,

d.setDate(d.getDate()-(d.getDay() ? d.getDay()-1 : 6));
d.setHours(0, 0, 0, 0);
like image 32
panda-34 Avatar answered Jan 08 '23 23:01

panda-34