Get the local date instead of UTC - javascript

The following script calculates me next Friday and next Sunday date.
The problem : the use of .toISOString uses UTC time. I need to change with something that outputs local time. I'm very new to javascript so I can't find the right property to use instead of .toIsostring.
What should I do ?
function nextWeekdayDate(date, day_in_week) {
var ret = new Date(date || new Date());
ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
return ret;
}
let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);
console.log('Next Friday : ' + nextFriday.toDateString() +
'\nFollowing Sunday: ' + followingSunday.toDateString());
/* Previous code calculates next friday and next sunday dates */
var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');

If you worry that the date is wrong in some timezones, try normalising the time
To NOT use toISO you can do this
const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB',
{ year: 'numeric', month: '2-digit', day: '2-digit' })
.split("/")
function nextWeekdayDate(date, day_in_week) {
var ret = new Date(date || new Date());
ret.setHours(15, 0, 0, 0); // normalise
ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
return ret;
}
let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);
console.log('Next Friday : ' + nextFriday.toDateString() +
'\nFollowing Sunday: ' + followingSunday.toDateString());
/* Previous code calculates next friday and next sunday dates */
var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');
console.log(yyyy, mm, dd)
// not using UTC:
const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB', { year: 'numeric', month: '2-digit', day: '2-digit' }).split("/")
console.log(yyyy1, mm1, dd1)

You are concerned that the [yyyy,mm,dd] is in UTC and not in current timzone?
The nextFriday is a date object. Would it work if you use the get-functions instead?
e.g.
const nextFridayYear = nextFriday.getFullYear();
// get month is zero index based, i have added one
const nextFridayMonth = (nextFriday.getMonth() + 1).toString()
.padStart(2, '0');
const nextFridayDay = today.getDate().toString()
.padStart(2, '0');

Related

Getting the start of the day in a different timezone

I have a Date. It is in the local timezone. I want a new Date that is at the beginning of the dayin a different timezone. Here are some things I do not want:
A Date in UTC equivalent to the first date converted to UTC
A string
Specifically, UTC does not work because getting the start of a day in UTC is not the same as getting the start of the day in a timezone.
So If I have a date in Calcutta and want to get the start of that day in San Francisco, the date in Calcutta and the date in Greenwich might not be the same date. It could be June 15th in Calcutta, June 15th in Greenwich, but June 2nd in San Francisco. So calling setMinutes(0) etc on a date that is set to UTC will not work.
I am also using date-fns (not moment) if that's helpful, but it doesn't seem to be because all dates (including those in date-fns-tz) are returned in either local or UTC time.)
Is this possible in Javascript or am I insane?
Note:
This is not the same as Convert date to another timezone in JavaScript
That is about converting to strings. I do not want strings.
One way is to:
Get the current timezone offset at the required location
Create a date for the required UTC date
Apply the offset from #1
e.g. using the answer at Get Offset of the other Location in Javascript:
function getTimezoneOffset(date, loc) {
let offset;
['en','fr'].some(lang => {
let parts = new Intl.DateTimeFormat(lang, {
minute: 'numeric',
timeZone: loc,
timeZoneName:'short'
}).formatToParts(date);
let tzName = parts.filter(part => part.type == 'timeZoneName' && part.value);
if (/^(GMT|UTC)/.test(tzName[0].value)) {
offset = tzName[0].value.replace(/GMT|UTC/,'') || '+0';
return true;
}
});
let sign = offset[0] == '\x2b'? '\x2b' : '\x2d';
let [h, m] = offset.substring(1).split(':');
return sign + h.padStart(2, '0') + ':' + (m || '00');
}
// Convert offset string in ±HH:mm to minutes
function offsetToMins(offset) {
let sign = /^-/.test(offset)? -1 : 1;
let [h, m] = offset.match(/\d\d/g);
return sign * (h * 60 + Number(m));
}
// Format date as YYYY-MM-DD at loc
function formatYMD(loc, date) {
let z = n => ('0'+n).slice(-2);
let {year, month, day} = new Intl.DateTimeFormat('en',{timeZone: loc})
.formatToParts(date)
.reduce((acc, part) => {
acc[part.type] = part.value;
return part;
}, Object.create(null));
return `${year}-${z(month)}-${z(day)}`
}
// Return stat of day for date at loc
function startOfDayAtLoc(loc, date = new Date()) {
let offset = getTimezoneOffset(date, loc);
let offMins = offsetToMins(offset);
let d = new Date(+date);
d.setUTCHours(0, -offMins, 0, 0);
// If date is + or - original date, adjust
let oDateTS = formatYMD(loc, date);
let sodDateTS = formatYMD(loc, d);
if (sodDateTS > oDateTS) {
d.setUTCDate(d.getUTCDate() - 1);
} else if (sodDateTS < oDateTS) {
d.setUTCDate(d.getUTCDate() + 1);
}
return d;
}
// QnD formatter
let f = (loc, d) => d.toLocaleString('en-gb', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour12:false,
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZone: loc,
timeZoneName: 'long'
});
// Examples
// 1 June 2020 00:00:00 Z
let d = new Date(Date.UTC(2020, 5, 1));
['America/New_York',
'Asia/Tokyo',
'Pacific/Tongatapu',
'Pacific/Rarotonga'
].forEach(loc => {
let locD = startOfDayAtLoc(loc, d);
console.log(loc + ' ' + getTimezoneOffset(d, loc) +
'\nZulu : ' + locD.toISOString() +
'\nLocal: ' + f(loc, locD));
});
// Dates on different date to UTC date
let laDate = new Date('2022-04-30T18:00:00-07:00');
let la = 'America/Los_Angeles';
console.log(`${la} - ${f(la, laDate)}` +
`\nStart of day: ${f(la, startOfDayAtLoc(la, laDate))}`
);
let chaDate = new Date('2022-05-01T03:00:00+10:00');
let cha = 'Pacific/Chatham';
console.log(`${cha} - ${f(cha, chaDate)}` +
`\nStart of day: ${f(cha, startOfDayAtLoc(cha, chaDate))}`
);
However, I'd suggest you use a library with timezone support as there are many quirks with the Date object and there is a new Temporal object in the works.

How to use toLocaleTimeString 12 hours time without AM/PM abbreviations?

I want to show time in 12 hours format without using the AM and PM. For example 3:45 only and not 3:45 PM or 3:45 AM. How I can modify the toLocaleTimeString() to not show the PM AM but in 12 number format?
var minsToAdd = 45;
var time = "15:00";
var newTime = new Date(new Date("2000/01/01 " + time).getTime() + minsToAdd * 60000).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true });
console.log(newTime);
.toLocaleTimeString() did not have any override to do so.
There are multiple ways to do so.
Replace AM/PM by blank:
var minsToAdd = 45;
var time = "15:00";
var newTime = new Date(new Date("2000/01/01 " + time).getTime() + minsToAdd * 60000).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true });
console.log(newTime.replace("AM","").replace("PM",""));
Using custom JavaScript function:
function formatTime(d) {
function z(n){return (n<10?'0':'')+n}
var h = d.getHours();
return (h%12 || 12) + ':' + z(d.getMinutes());
}
var minsToAdd = 45;
var time = "15:00";
var newTime = new Date(new Date("2000/01/01 " + time).getTime() + minsToAdd * 60000);
console.log(formatTime(newTime));
formats below assume the local time zone of the locale;
America/Los_Angeles for the US
US English uses 12-hour time with AM/PM
console.log(date.toLocaleTimeString('en-US'));
"7:00:00 PM"
For more information, visit official docs here
it's very ez.
const date24 = new Date();
const data24Time = date24.toLocaleTimeString('en-IT', { hour12: false })
console.log("24 h : ",data24Time)
// 24 h : 20:26:09
const date12 = new Date();
const data12Time = date12.toLocaleTimeString('en-IT')
console.log("12 h : ",data12Time)
// 12 h : 8:26:09 PM
// toLocaleTimeString('{languege for show time}-{languege for set}')

group by weeks,days and year javascript [duplicate]

I have today = new Date(); object. I need to get first and last day of the current week. I need both variants for Sunday and Monday as a start and end day of the week. I am little bit confuse now with a code. Can your help me?
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
firstday
"Sun, 06 Mar 2011 12:25:40 GMT"
lastday
"Sat, 12 Mar 2011 12:25:40 GMT"
This works for firstday = sunday of this week and last day = saturday for this week. Extending it to run Monday to sunday is trivial.
Making it work with first and last days in different months is left as an exercise for the user
Be careful with the accepted answer, it does not set the time to 00:00:00 and 23:59:59, so you can have problems.
You can use a third party date library to deal with dates. For example:
var startOfWeek = moment().startOf('week').toDate();
var endOfWeek = moment().endOf('week').toDate();
EDIT: As of September 2020, using Moment is discouraged for new projects (blog post)
Another popular alternative is date-fns.
You can also use following lines of code to get first and last date of the week:
var curr = new Date;
var firstday = new Date(curr.setDate(curr.getDate() - curr.getDay()));
var lastday = new Date(curr.setDate(curr.getDate() - curr.getDay()+6));
Hope it will be useful..
The excellent (and immutable) date-fns library handles this most concisely:
const start = startOfWeek(date);
const end = endOfWeek(date);
Default start day of the week is Sunday (0), but it can be changed to Monday (1) like this:
const start = startOfWeek(date, {weekStartsOn: 1});
const end = endOfWeek(date, {weekStartsOn: 1});
Here's a quick way to get first and last day, for any start day.
knowing that:
1 day = 86,400,000 milliseconds.
JS dates values are in milliseconds
Recipe: figure out how many days you need to remove to get the your week's start day (multiply by 1 day's worth of milliseconds). All that is left after that is to add 6 days to get your end day.
var startDay = 1; //0=sunday, 1=monday etc.
var d = now.getDay(); //get the current day
var weekStart = new Date(now.valueOf() - (d<=0 ? 7-startDay:d-startDay)*86400000); //rewind to start day
var weekEnd = new Date(weekStart.valueOf() + 6*86400000); //add 6 days to get last day
Small change to #Chris Lang answer.
if you want Monday as the first day use this.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay()+ (this.getDay() == 0 ? -6:1) )));
}
Date.prototype.GetLastDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay() +7)));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
Thaks #Chris Lang
This works across year and month changes.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay())));
}
Date.prototype.GetLastDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay() +6)));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
You could do something like this
var today = new Date();
var startDay = 0;
var weekStart = new Date(today.getDate() - (7 + today.getDay() - startDay) % 7);
var weekEnd = new Date(today.getDate() + (7 - today.getDay() - startDay) % 7);
Where startDay is a number from 0 to 6 where 0 stands for Sunday (ie 1 = Monday, 2 = Tuesday, etc).
SetDate will sets the day of the month. Using setDate during start and end of the month,will result in wrong week
var curr = new Date("08-Jul-2014"); // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var firstday = new Date(curr.setDate(first)); // 06-Jul-2014
var lastday = new Date(curr.setDate(last)); //12-Jul-2014
If u setting Date is 01-Jul-2014, it will show firstday as 29-Jun-2014 and lastday as 05-Jun-2014 instead of 05-Jul-2014
So overcome this issue i used
var curr = new Date();
day = curr.getDay();
firstday = new Date(curr.getTime() - 60*60*24* day*1000); //will return firstday (ie sunday) of the week
lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000); //adding (60*60*6*24*1000) means adding six days to the firstday which results in lastday (saturday) of the week
I recommend to use Moment.js for such cases. I had scenarios where I had to check current date time, this week, this month and this quarters date time. Above an answer helped me so I thought to share rest of the functions as well.
Simply to get current date time in specific format
case 'Today':
moment().format("DD/MM/YYYY h:mm A");
case 'This Week':
moment().endOf('isoweek').format("DD/MM/YYYY h:mm A");
Week starts from Sunday and ends on Saturday if we simply use 'week' as parameter for endOf function but to get Sunday as the end of the week we need to use 'isoweek'.
case 'This Month':
moment().endOf('month').format("DD/MM/YYYY h:mm A");
case 'This Quarter':
moment().endOf('quarter').format("DD/MM/YYYY h:mm A");
I chose this format as per my need. You can change the format according to your requirement.
//get start of week; QT
function _getStartOfWeek (date){
var iDayOfWeek = date.getDay();
var iDifference = date.getDate() - iDayOfWeek + (iDayOfWeek === 0 ? -6:1);
return new Date(date.setDate(iDifference));
},
function _getEndOfWeek(date){
return new Date(date.setDate(date.getDate() + (7 - date.getDay()) === 7 ? 0 : (7 - date.getDay()) ));
},
*current date == 30.06.2016 and monday is the first day in week.
It also works for different months and years.
Tested with qunit suite:
QUnit.module("Planung: Start of week");
QUnit.test("Should return start of week based on current date", function (assert) {
var startOfWeek = Planung._getStartOfWeek(new Date());
assert.ok( startOfWeek , "returned date: "+ startOfWeek);
});
QUnit.test("Should return start of week based on a sunday date", function (assert) {
var startOfWeek = Planung._getStartOfWeek(new Date("2016-07-03"));
assert.ok( startOfWeek , "returned date: "+ startOfWeek);
});
QUnit.test("Should return start of week based on a monday date", function (assert) {
var startOfWeek = Planung._getStartOfWeek(new Date("2016-06-27"));
assert.ok( startOfWeek , "returned date: "+ startOfWeek);
});
QUnit.module("Planung: End of week");
QUnit.test("Should return end of week based on current date", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date());
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on sunday date with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-07-03"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on monday date with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-27"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 01-06-2016 with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-01"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 21-06-2016 with different month", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-06-21"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 28-12-2016 with different month and year", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-12-28"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
QUnit.test("Should return end of week based on 01-01-2016 with different month and year", function (assert) {
var endOfWeek = Planung._getEndOfWeek(new Date("2016-01-01"));
assert.ok( endOfWeek , "returned date: "+ endOfWeek);
});
var dt = new Date() //current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay-1
var wkStart = new Date(new Date(dt).setDate(dt.getDate()- lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate()+6));
This will be useful for any date scenario.
Just using pure javascript, you can use the function below to get first day and last day of a week with freely setting day for start of week.
var weekday = [];
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
function getFirstDayOfWeek(date, from) {
//Default start week from 'Sunday'. You can change it yourself.
from = from || 'Sunday';
var index = weekday.indexOf(from);
var start = index >= 0 ? index : 0;
var d = new Date(date);
var day = d.getDay();
var diff = d.getDate() - day + (start > day ? start - 7 : start);
d.setDate(diff);
return d;
};
Last day of week is just 6 days after first day of week
function getLastDayOfWeek(date, from) {
from = from || 'Sunday';
var index = weekday.indexOf(from);
var start = index >= 0 ? index : 0;
var d = new Date(date);
var day = d.getDay();
var diff = d.getDate() - day + (start > day ? start - 1 : 6 + start);
d.setDate(diff);
return d;
};
Test:
getFirstDayOfWeek('2017-10-16'); //--> Sun Oct 15 2017
getFirstDayOfWeek('2017-10-16', 'Monday'); //--> Mon Oct 16 2017
getFirstDayOfWeek('2017-10-16', 'Tuesday'); //--> Tue Oct 10 2017
The biggest issue when the given date's week is in-between two months. (Like 2022-07-01, it's the 5th day of the week.)
Using getDay function we check if the week is in-between months.
Note: getDay() function identifies week start day as sunday, so it'll return 0 for sunday.
var curr = new Date(); // get current date
var weekdaynum = curr.getDay();
if(weekdaynum == 0){ //to change sunday to the last day of the week
weekdaynum = 6;
} else{
weekdaynum = weekdaynum-1;
}
var firstweek = curr.getDate() - weekdaynum;
var lastweek = firstweek + 6; // last day is the first day + 6
if((curr.getDate()-weekdaynum) <= 0){
var firstweek_lasmonth_lastdate = new Date(currweek.getFullYear(),currweek.getMonth(), 0);
var firstweek_diff = firstweek_lasmonth_lastdate.getDate()-Math.abs(firstweek);
var firstweekday = new Date(currweek.getFullYear(),currweek.getMonth()-1,firstweek_lasmonth_lastdate.getDate()+firstweek_diff);
var lastweekday = new Date(currweek.getFullYear(),currweek.getMonth()-1,firstweek_lasmonth_lastdate.getDate()+firstweek_diff+7);
} else{
var firstweekday = new Date(curr.setDate(firstweek));
var lastweekday = new Date(curr.setDate(lastweek));
}
So this will return (given date is: 2022/07/01):
firstweekday = Mon Jun 27 2022 00:00:00
lastweekday = Sun Jul 03 2022 00:00:00
Hope this helps.
krtek's method has some wrong,I tested this
var startDay = 0;
var weekStart = new Date(today.getDate() - (7 + today.getDay() - startDay) % 7);
var weekEnd = new Date(today.getDate() + (6 - today.getDay() - startDay) % 7);
it works
Although the question is seeming as obsolete I have to point out a problem.
Question: What will happen at 1st January 2016?
I think most of the above solutions calculate start of week as 27.12.2016.
For this reason I think, the correct calculation should be like the below simply;
var d = new Date(),
dayInMs = 1000 * 60 * 60 * 24,
weekInMs = dayInMs * 7,
startOfToday = new Date(d.getFullYear(), d.getMonth(), d.getDate()).valueOf(),
todayElapsedTime = d.valueOf() - startOfToday,
dayDiff = d.getDay() * dayInMs,
dateDiff = dayDiff + todayElapsedTime,
// finally
startOfWeek = d.valueOf() - dateDiff,
endOfWeek = startOfWeek + weekInMs - 1;
JavaScript
function getWeekDays(curr, firstDay = 1 /* 0=Sun, 1=Mon, ... */) {
var cd = curr.getDate() - curr.getDay();
var from = new Date(curr.setDate(cd + firstDay));
var to = new Date(curr.setDate(cd + 6 + firstDay));
return {
from,
to,
};
};
TypeScript
export enum WEEK_DAYS {
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
}
export const getWeekDays = (
curr: Date,
firstDay: WEEK_DAYS = WEEK_DAYS.Monday
): { from: Date; to: Date } => {
const cd = curr.getDate() - curr.getDay();
const from = new Date(curr.setDate(cd + firstDay));
const to = new Date(curr.setDate(cd + 6 + firstDay));
return {
from,
to,
};
};
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:1); // adjust when day is sunday
return new Date(d.setDate(diff));
}
console.log( getMonday(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate())) ) // Mon Nov 08 2010
Pure vanilla JS. no third party libraries.
const now = new Date()
const startOfWeek = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay())
const endOfWeek = new Date(now.getFullYear(), now.getMonth(), startOfWeek.getDate() + 7)
^ this returns Sunday 00am to Sunday 00am. Adjust the "7" to get what you want.
var currentDate = new Date();
var firstday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay())).toUTCString();
var lastday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 6)).toUTCString();
console.log("firstday", firstday);
console.log("lastday", lastday);
Works with different months and years.
let wDate = new Date();
let dDay = wDate.getDay() > 0 ? wDate.getDay() : 7;
let first = wDate.getDate() - dDay + 1;
let firstDayWeek = new Date(wDate.setDate(first));
let lastDayWeek = new Date(wDate.setDate(firstDayWeek.getDate()+6));
console.log(firstDayWeek.toLocaleDateString());
console.log(lastDayWeek.toLocaleDateString());
Nice suggestion but you got a small problem in lastday.
You should change it to:
lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000);
The moment approach worked for me for all the cases ( although i have not test the boundaries like year end , leap years ). Only Correction in the above code is the parameter is "isoWeek" , if you want to start the week from Monday.
let startOfWeek = moment().startOf("isoWeek").toDate();
let endOfWeek = moment().endOf("isoWeek").toDate();
We have added jquery code that shows the current week of days from monday to sunday.
var d = new Date();
var week = [];
var _days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var _months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
for (let i = 1; i <= 7; i++) {
let first = d.getDate() - d.getDay() + i;
let dt = new Date(d.setDate(first));
var _day = _days[dt.getDay()];
var _month = _months[dt.getMonth()];
var _date = dt.getDate();
if(_date < 10 ){
_date = '0' +_date;
}
var _year = dt.getFullYear();
var fulldate = _day+' '+_month+' '+_date+' '+_year+' ';
week.push(fulldate);
}
console.log(week);
An old question with lots of answers, so another one won't be an issue. Some general functions to get the start and end of all sorts of time units.
For startOf and endOf week, the start day of the week defaults to Sunday (0) but any day can be passed (Monday - 1, Tuesday - 2, etc.). Only uses Gregorian calendar though.
The functions don't mutate the source date, so to see if a date is in the same week as some other date (week starting on Monday):
if (d >= startOf('week', d1, 1) && d <= endOf('week', d1, 1)) {
// d is in same week as d1
}
or in the current week starting on Sunday:
if (d >= startOf('week') && d <= endOf('week')) {
// d is in the current week
}
// Returns a new Date object set to start of given unit
// For start of week, accepts any day as start
function startOf(unit, date = new Date(), weekStartDay = 0) {
// Copy original so don't modify it
let d = new Date(date);
let e = new Date(d);
e.setHours(23,59,59,999);
// Define methods
let start = {
second: d => d.setMilliseconds(0),
minute: d => d.setSeconds(0,0),
hour : d => d.setMinutes(0,0,0),
day : d => d.setHours(0,0,0,0),
week : d => {
start.day(d);
d.setDate(d.getDate() - d.getDay() + weekStartDay);
if (d > e) d.setDate(d.getDate() - 7);
},
month : d => {
start.day(d);
d.setDate(1);
},
year : d => {
start.day(d);
d.setMonth(0, 1);
},
decade: d => {
start.year(d);
let year = d.getFullYear();
d.setFullYear(year - year % 10);
},
century: d => {
start.year(d);
let year = d.getFullYear();
d.setFullYear(year - year % 100);
},
millenium: d => {
start.year(d);
let year = d.getFullYear();
d.setFullYear(year - year % 1000);
}
}
start[unit](d);
return d;
}
// Returns a new Date object set to end of given unit
// For end of week, accepts any day as start day
// Requires startOf
function endOf(unit, date = new Date(), weekStartDay = 0) {
// Copy original so don't modify it
let d = new Date(date);
let e = new Date(date);
e.setHours(23,59,59,999);
// Define methods
let end = {
second: d => d.setMilliseconds(999),
minute: d => d.setSeconds(59,999),
hour : d => d.setMinutes(59,59,999),
day : d => d.setHours(23,59,59,999),
week : w => {
w = startOf('week', w, weekStartDay);
w.setDate(w.getDate() + 6);
end.day(w);
d = w;
},
month : d => {
d.setMonth(d.getMonth() + 1, 0);
end.day(d);
},
year : d => {
d.setMonth(11, 31);
end.day(d);
},
decade: d => {
end.year(d);
let y = d.getFullYear();
d.setFullYear(y - y % 10 + 9);
},
century: d => {
end.year(d);
let y = d.getFullYear();
d.setFullYear(y - y % 100 + 99);
},
millenium: d => {
end.year(d);
let y = d.getFullYear();
d.setFullYear(y - y % 1000 + 999);
}
}
end[unit](d);
return d;
}
// Examples
let d = new Date();
['second','minute','hour','day','week','month','year',
'decade','century','millenium'].forEach(unit => {
console.log(('Start of ' + unit).padEnd(18) + ': ' +
startOf(unit, d).toString());
console.log(('End of ' + unit).padEnd(18) + ': ' +
endOf(unit, d).toString());
});
var currentDate = new Date();
var firstday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay())).toUTCString();
var lastday = new Date(currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 7)).toUTCString();
console.log(firstday, lastday)
I'm using the following code in but because of .toUTCString() i'm receiving the following error as show in image.
if i remove .toUTCString(). output which i receive is not as expected
Small change to #SHIVA's answer which is a changed #Chris Lang answer.
For monday first usage with fix when today is sunday.
Date.prototype.GetFirstDayOfWeek = function() {
return (new Date(this.setDate(this.getDate() - this.getDay()+ (this.getDay() == 0 ? -6:1) )));
}
Date.prototype.GetLastDayOfWeek = function() {
return new Date(this.setDate(this.getDate() - (this.getDay() == 0 ? 7 : this.getDay()) + 7));
}
var today = new Date();
alert(today.GetFirstDayOfWeek());
alert(today.GetLastDayOfWeek());
You can try the below one too
let weekBgnDt = new Date();
let weekEndDt = new Date();
let wBeginDateLng, wEndDateLng, diffDays,dateCols=[];
if (weekBgnDt.getDay() > 0) {
diffDays = 0 - weekBgnDt.getDay();
weekBgnDt.setDate(weekBgnDt.getDate() + diffDays)
}
weekEndDt = weekEndDt.setDate(weekBgnDt.getDate() + 6)
wBeginDate = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: '2-digit' }).format(weekBgnDt);
wEndDate = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric', month:
'2-digit' }).format(weekEndDt);
wBeginDateLng = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: 'long' }).format(weekBgnDt);
wEndDateLng = new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: 'long' }).format(weekEndDt);
console.log(wBeginDate, "-", wBeginDateLng)
console.log(wEndDate, "-", wEndDateLng)
for(let i=weekBgnDt;i<=weekEndDt;){
dateCols.push(new Intl.DateTimeFormat('en-GB', { day: 'numeric', year: 'numeric',
month: '2-digit' }).format(i));
i=weekBgnDt.setDate(weekBgnDt.getDate()+1)
}
console.log({wBeginDate,wBeginDateLng,wEndDate,wEndDateLng,dateCols})
The result will be printed as
{ wBeginDate: "16/05/2021", wBeginDateLng: "16 May 2021", wEndDate: "22/05/2021", wEndDateLng: "22 May 2021", dateCols: Array ["16/05/2021", "17/05/2021", "18/05/2021", "19/05/2021", "20/05/2021", "21/05/2021", "22/05/2021"] }
The right way to get the first and last date of the current week with appropriate month & year is as below
const curr = new Date();
const first = curr.getDate() - curr.getDay() + 1; // Start from Monday
const firstDate = new Date(curr.setDate(first));
const lastDate = new Date(curr.setDate(firstDate.getDate() + 6));
console.log(firstDate.toLocaleDateString(), lastDate.toLocaleDateString());
You can use this function, it works with first and last day of the week in different months or years
const getFirstAndLastDayOfTheWeek = () => {
// The starting time is the same current
let a = new Date();
let b = new Date();
const weekDay = a.getDay();
if (weekDay === 0) {
a.setDate(a.getDate() - 6);
} else if (weekDay === 1) {
b.setDate(b.getDate() + 7 - b.getDay());
} else if (weekDay >= 1) {
a.setDate(a.getDate() - a.getDay() + 1);
b.setDate(b.getDate() + 7 - b.getDay());
}
return { firstWeekDate: a, lastWeekDate: b };
}
console.log(getFirstAndLastDayOfTheWeek());

Timestamp to human readable format

Well I have a strange problem while convert from unix timestamp to human representation using javascript
Here is timestamp
1301090400
This is my javascript
var date = new Date(timestamp * 1000);
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDay();
var hour = date.getHours();
var minute = date.getMinutes();
var seconds = date.getSeconds();
I expected results to be 2011 2, 25 22 00 00. But it is 2011, 2, 6, 0, 0, 0
What I miss ?
getDay() returns the day of the week. To get the date, use date.getDate(). getMonth() retrieves the month, but month is zero based, so using getMonth() + 1 should give you the right month. Time value seems to be ok here, albeit the hour is 23 here (GMT+1). If you want universal values, add UTC to the methods (e.g. date.getUTCFullYear(), date.getUTCHours())
const timestamp = 1301090400;
const date = new Date(timestamp * 1000);
const datevalues = [
date.getFullYear(),
date.getMonth()+1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
];
alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]
Here is a small helper idea to retrieve values of a given Date:
const dateHelper = dateHelperFactory();
const formatMe = date => {
const vals = `yyyy,mm,dd,hh,mmi,ss,mms`.split(`,`);
const myDate = dateHelper(date).toArr(...vals);
return `${myDate.slice(0, 3).join(`/`)} ${
myDate.slice(3, 6).join(`:`)}.${
myDate.slice(-1)[0]}`;
};
// to a formatted date with zero padded values
console.log(formatMe(new Date(1301090400 * 1000)));
// the raw values
console.log(dateHelper(new Date(1301090400 * 1000)).values);
function dateHelperFactory() {
const padZero = (val, len = 2) => `${val}`.padStart(len, `0`);
const setValues = date => {
let vals = {
yyyy: date.getFullYear(),
m: date.getMonth()+1,
d: date.getDate(),
h: date.getHours(),
mi: date.getMinutes(),
s: date.getSeconds(),
ms: date.getMilliseconds(), };
Object.keys(vals).filter(k => k !== `yyyy`).forEach(k =>
vals[k[0]+k] = padZero(vals[k], k === `ms` && 3 || 2) );
return vals;
};
return date => ( {
values: setValues(date),
toArr(...items) { return items.map(i => this.values[i]); },
} );
}
.as-console-wrapper {
max-height: 100% !important;
}
Or see this small stackblitz project (a little bit more efficient).
var newDate = new Date();
newDate.setTime(unixtime*1000);
dateString = newDate.toUTCString();
Where unixtime is the time returned by your sql db. Here is a fiddle if it helps.
For example, using it for the current time:
document.write( new Date().toUTCString() );
here is kooilnc's answer w/ padded 0's
function getFormattedDate() {
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
month = (month < 10 ? "0" : "") + month;
day = (day < 10 ? "0" : "") + day;
hour = (hour < 10 ? "0" : "") + hour;
min = (min < 10 ? "0" : "") + min;
sec = (sec < 10 ? "0" : "") + sec;
var str = date.getFullYear() + "-" + month + "-" + day + "_" + hour + ":" + min + ":" + sec;
/*alert(str);*/
return str;
}
use Date.prototype.toLocaleTimeString() as documented here
please note the locale example en-US in the url.
I was looking for a very specific solution for returning the current time as a guaranteed length string to prepend at the beginning of every log line. Here they are if someone else is looking for the same thing.
Basic Timestamp
"2021-05-26 06:46:33"
The following function returns a zero padded timestamp for the current time (always 19 characters long)
function getTimestamp () {
const pad = (n,s=2) => (`${new Array(s).fill(0)}${n}`).slice(-s);
const d = new Date();
return `${pad(d.getFullYear(),4)}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
Full Timestamp
"2021-06-02 07:08:19.041"
The following function returns a zero padded timestamp for the current time including milliseconds (always 23 characters long)
function getFullTimestamp () {
const pad = (n,s=2) => (`${new Array(s).fill(0)}${n}`).slice(-s);
const d = new Date();
return `${pad(d.getFullYear(),4)}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(),3)}`;
}
Hours, minutes and seconds depend on the time zone of your operating system. In GMT (UST) it's 22:00:00 but in different timezones it can be anything. So add the timezone offset to the time to create the GMT date:
var d = new Date();
date = new Date(timestamp*1000 + d.getTimezoneOffset() * 60000)
To direct get a readable local timezone:
var timestamp = 1301090400,
date = new Date(timestamp * 1000)
document.write( date.toLocaleString() );
I'm too late to the party since this question is already a decade old, but I want to provide a cleaner one without the use of any plugins like moment.js. only vanilla javascript.
export default {
// Accepts "1998-08-06 11:00:00" <-- This is UTC timestamp
getFormalDateTime(utcDate) {
const formattedUtc = utcDate.split(' ').join('T')+'Z'
let date = new Date(formattedUtc);
if (date.toString() === "Invalid Date")
return "N/A";
let dateString = date.toLocaleDateString("en-US", {month: 'long', day: 'numeric', year: 'numeric'});
let timeString = date.toLocaleTimeString("en-US", {hour: 'numeric', minute: 'numeric', hour12: true});
let formattedDate = dateString + " | " + timeString;
return formattedDate; // Returns "August 6, 1998 | 11:00 AM" <-- This is converted to client time zone.
},
// Accepts: "1998-08-06"
getFormalDate(convertDate) {
let date = new Date(convertDate);
if (date.toString() === "Invalid Date")
return "N/A";
let dateString = date.toLocaleDateString("en-US", {month: 'long', day: 'numeric', year: 'numeric'});
return dateString // Returns "August 6, 1998"
}
}
My code is formatted for ES6 modules because I use it as a module for my vuejs project but you can convert it to a normal javascript function.
getFormalDateTime('1998-08-06 11:00:00') the parameter should be in UTC time. This will return a formal date time converted to the client/browser timezone: August 6, 1998 | 11:00 AM
getFormalDate('1998-08-06') will just return August 6, 1998
More information here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

Getting the previous month's first date from current date in JavaScript

Please anyone share the code to find the previous month's first date from current date in JavaScript. For example, if the current date is 25th Jan 2009, I should get 1st Dec 2008 as result.
Straightforward enough, with the date methods:
var x = new Date();
x.setDate(1);
x.setMonth(x.getMonth()-1);
Simplest way would be:
var x = new Date();
x.setDate(0); // 0 will result in the last day of the previous month
x.setDate(1); // 1 will result in the first day of the month
Deals with updating year when moving from January to December
var prevMonth = function(dateObj) {
var tempDateObj = new Date(dateObj);
if(tempDateObj.getMonth) {
tempDateObj.setMonth(tempDateObj.getMonth() - 1);
} else {
tempDateObj.setYear(tempDateObj.getYear() - 1);
tempDateObj.setMonth(12);
}
return tempDateObj
};
var wrapper = document.getElementById('wrapper');
for(var i = 0; i < 12; i++) {
var x = new Date();
var prevDate = prevMonth(x.setMonth(i));
var div = document.createElement('div');
div.textContent =
"start month/year: " + i + "/" + x.getFullYear() +
" --- prev month/year: " + prevDate.getMonth() +
"/" + prevDate.getFullYear() +
" --- locale prev date: " + prevDate.toLocaleDateString();
wrapper.appendChild(div);
}
<div id='wrapper'>
</div>
Important Note: Some of the answers using setMonth() here are wrong:
One liners for use in 2019 (using ES6 syntax; supported by all major browsers and Node):
const date = new Date().toISOString(); // "2019-09-18T13:49:12.775Z"
const [yyyy, mm, dd, h, i, s] = date.split(/T|:|-/);
// previous month's last day
const prev = new Date(new Date().setDate(0)).toISOString();
const [pyyyy, pmm] = prev.split(/T|:|-/);
Note that Array destructuring allows you to skip parts:
const date = new Date().toISOString();
const [, , dd, , i] = date.split(/T|:|-/);
Explanation: The code above gets the ISO date 2019-09-18T13:49:12.775Z and splits it on : or - or T which returns an array [2019, 09, 18, 13, 49, 12] which then gets destructured.
Using setMonth() is wrong:
date = new Date("Dec 31, 2019")
date.setMonth(date.getMonth() - 1);
date; // Dec 1, 2019!
This worked for me
var curDateMonth = new Date();
var prvDateMonth = new Date(curDateMonth.getFullYear(),curDateMonth.getMonth()-1,curDateMonth.getMonth());
console.log(curDateMonth.toLocaleString('en-US', { month: 'long' }) +' vs '+ prvDateMonth.toLocaleString('en-US', { month: 'long' }));
Check this link:
http://blog.dansnetwork.com/2008/09/18/javascript-date-object-adding-and-subtracting-months/
EDIT: I have drummed up an example:
Date.prototype.SubtractMonth = function(numberOfMonths) {
var d = this;
d.setMonth(d.getMonth() - numberOfMonths);
d.setDate(1);
return d;
}
$(document).ready(function() {
var d = new Date();
alert(d.SubtractMonth(1));
});
To get 00:00:00 am of previous month use this:
let d = new Date();
d.setDate(1);
d.setMonth(d.getMonth() - 1);
d.setHours(0,0,0,0);
const lastMonthStart = new Date(d);
Hope this helps!!
// Previous Month Detail
let prevStartDate = new Date(this.date.getFullYear(), this.date.getMonth() - 1, 1);
console.log(prevStartDate);
let preEndDate = new Date(this.date.getFullYear(), this.date.getMonth() - 1 + 1, 0);
console.log(preEndDate);
//Current Month Detail
let cStartDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1);
console.log(cStartDate);
let cEndDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0);
console.log(cEndDate);
//Next Month Detail
let nStartDate = new Date(this.date.getFullYear(), this.date.getMonth() + 1, 1);
console.log(nStartDate);
let nendDate = new Date(this.date.getFullYear(), this.date.getMonth() + 1 + 1, 0);
console.log(nendDate);
//just try this will work fine
let date = new Date();
let month = new Date().getMonth();
let prevMonth = date.setMonth(month - 1)
let formatPrevMonth = new Date(date.setMonth(month - 1));
console.log(formatPrevMonth)
Here, first we assign getMonth() to a variable and incremented it by 1:
var currentMonth = date.getMonth()+1;
var current_date = date.getFullYear()+"/"+currentMonth+"/"+date.getDate();
document.getElementById("p3").innerHTML = "Today,s date:"+current_date;
This can easily be achieved by creating a Date object based on the input date object and changing the date to 1, decrementing the year if it was January and decrementing the month (modulo 12). An important addition to it is to subtract the offset as well.
function getFirstOfPreviousMonth(date) {
let result = new Date(date.getFullYear() - (date.getMonth() ? 0 : 1), (date.getMonth() + 11) % 12, 1);
return new Date(result.getTime() - result.getTimezoneOffset() * 60000);
}
console.log(getFirstOfPreviousMonth(new Date()));
console.log(getFirstOfPreviousMonth(new Date(2009, 0, 25)));

Categories