amit
amit

Reputation: 10261

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.

Upvotes: 5

Views: 24751

Answers (4)

kennebec
kennebec

Reputation: 104760

You can return the local time string or the GMT time string for any Date object by adjusting the local time accordingly:

// 1. Monday(00:00:00 Local time)
    var mon= new Date();
    mon.setHours(0, 0, 0, 0);
    var d= mon.getDate();
    while(mon.getDay()!= 1) mon.setDate(--d);

    alert(mon.toLocaleString());

    /*  returned value: (String)
    Monday, March 26, 2012 12:00:00 AM
    */

// 2. Monday(00:00:00 GMT)
    var umon= new Date();
    umon.setUTCHours(0, 0, 0, 0);
    var d= umon.getUTCDate();
    while(umon.getUTCDay()!= 1) umon.setUTCDate(--d);

    alert(umon.toUTCString())

    /*  returned value: (String)
    Mon, 26 Mar 2012 00:00:00 GMT
    */

In this example the two dates with the same basic string are 4 hours apart.

Upvotes: 0

aztechy
aztechy

Reputation: 640

You'll want to work with the UTC versions of the date getter functions.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getUTCDate

That will get you the day based on utc, rather than local time.

Upvotes: 0

panda-34
panda-34

Reputation: 4209

if you start your week on Monday,

d.setDate(d.getDate()-(d.getDay() ? d.getDay()-1 : 6));
d.setHours(0, 0, 0, 0);

Upvotes: 3

Pointy
Pointy

Reputation: 413702

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.

Upvotes: 12

Related Questions