javascript date of last day of previous month - javascript

Let's say I have 3 variables like this:
var Month = 8; // in reality, it's a parameter provided by some user input
var Year = 2011; // same here
var FirstDay = new Date(Year, Month, 1);
Now I want to have the value of the day before the first day of the month in a variable. I'm doing this:
var LastDayPrevMonth = (FirstDay.getDate() - 1);
It's not working as planned. What the right of doing it?
Thanks.

var LastDayPrevMonth = new Date(Year, Month, 0).getDate();

var LastDayPrevMonth = new Date(FirstDay);
LastDayPrevMonth.setHours(FirstDay.getHours()-24);

var FirstDay = new Date(Year, Month, 1);
var lastMonth = new Date(FirstDay);
lastMonth.setDate(-1);
alert(lastMonth);
And remember that 8 is Sept, not Aug in JavaScript. :)

If you need to calculate this based on today's date ( you want the last day of last month ), the following should help.
If you only care about the month/day/year, this is the simplest and fastest that I can think of:
var d = new Date(); d.setDate(0);
console.log(d);
If you want midnight of last day of the previous month, then:
var d = new Date(); d.setDate(0); d.setHours(0,0,0,0);
console.log(d);
If you want to know the last day of the previous month, based on provided year/month:
var year = 2016, month = 11;
var d = new Date(year, (month - 1)); d.setDate(0); d.setHours(0,0,0,0);
console.log(d);
After running any of the above, to get the YYYY-M-D format:
var str = d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
console.log(str);
To see additional methods available, and to see what they do, you can read the docs.

Create a new Date object and pass it the other date coerced to the number of milliseconds since the Unix epoch and then minus a whole day (in milliseconds).
var LastDayPrevMonth = new Date(FirstDay - 864e5);
Example:
var Month = 8; // in reality, it's a parameter provided by some user input
var Year = 2011; // same here
var FirstDay = new Date(Year, Month, 1);
var LastDayPrevMonth = new Date(FirstDay - 864e5);
document.body.innerHTML = LastDayPrevMonth;

Related

I calculated to get the first day of the month but go the last

I start by getting the date of the beginning of month:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
Then I convert it to ISO:
firstDay = firstDay.toISOString();
Why did I get 2019-05-31 as the first day instead of 2019-06-01?
You could use a simple regex to format the string using replace:
/(\d{4})-(\d{2})-(\d{2}).+/
// Set the inital date to a UTC date
var date = new Date(new Date().toLocaleString("en-US", {timeZone: "UTC"}))
// Update the day without affecting the month/day when using toISOString()
date.setDate(1)
// Format the date
let formatted = date.toISOString().replace(/(\d{4})-(\d{2})-(\d{2}).+/, '$3-$2-$1')
console.log(formatted)
The default javascript date uses your local timezone, by converting it to something else you can end up with a different date.
You can do it
var firstDay = new Date().toISOString().slice(0, 8) + '01';
console.log(firstDay);
The date object in javascript can be somewhat tricky. When you create a date, it is created in your local timezone, but toISOString() gets the date according to UTC. The following should convert the date to ISO but keep it in your own time zone.
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var day = 0;
if (firstDay.getDate() < 10) {
day = '0' + firstDay.getDate();
}
var month = 0;
if ((firstDay.getMonth() + 1) < 10) {
//months are zero indexed, so we have to add 1
month = '0' + (firstDay.getMonth() + 1);
}
firstDay = firstDay.getFullYear() + '-' + month + '-' + day;
console.log(firstDay);

Why does adding a month to a Date object return a strange number?

The following returns 11 which is correct.
var month = d.getMonth();
alert(month);
When I try adding a month to it returns something very different
var month = d.setMonth(d.getMonth() + 1);
alert(month);
It returns: 1513230546878
Return values of methods that you are using in your code are as follows
d.getMonth() - A Number, from 0 to 11, representing the month (Link)
d.setMonth() - A Number, representing the number of milliseconds between the date object and midnight January 1 1970 (Link)
Please note, d.setMonth() will modify your Date object in place. So, if you want your code to work as expected, you can write as follows
var d = new Date()
var month = d.getMonth();
alert(month);
d.setMonth(d.getMonth() + 1);
alert(d.getMonth());
d.setMonth() method returns the updated timestamp value (See docs). That's why you got a long number.
If you want to get the month you will use as per below
var d = new Date("2017-10-03");
d.setMonth(d.getMonth() + 1);
var month = d.getMonth(); // get new month
alert(month);
hope it helps
In java script, if you write this:
var month = d.setMonth(d.getMonth() + 1);
You get a timestamp. Meaning, an integer number representing the month you chose.
This is because, setDate accepts a dayValue parameter:
Date.setDate(dayValue)
Meaning that:
var dt = new Date("Aug 28, 2008 23:30:00");
dt.setDate(24);
console.log(dt);
will result in:
Sun Aug 24 2008 23:30:00 //+ your standard gmt time
For further inquire, see this Link
//set date to now:
var d = new Date();
console.log(d);
//just checking
var month = d.getMonth();
console.log(month);
//add a month
d.setMonth(d.getMonth() + 1);
//now the month is one ahead:
console.log(d.getMonth());
console.log(d);

How to get the Week wise Start and End date in angularjs

Before I am using angularjs-DatePicker from this npm.
Here,I am able to select the date from the date picker.But now I have to fields as FromDate and ToDate which means the week StartDate and EndDate should show when any date pick in that week.
Ex: Like in Calender 01-08-2017 Start on Tue, So whenever Selects Any date from 01 to 05 then the two fields should show as FromDate as 01 and TODate as 06 and in the same whenever the user selects the 31-07-2017 the the Two fields should show as 30 and 31 of july.
I have an idea to achieve the ToDate from FromDate Calender control onchange event in DotNet as like below mentioned code
Convert.ToDouble(objstart.DayOfWeek)).ToString("dd-MM-yyyy")
But how to achieve this usecase in the angularjs.
Thanks
Ok, so what I'd do is to calculate different dates, and take the min/max depending on the start or end of the week.
Here:
//Use the date received, UTC to prevent timezone making dates shift
var pickedDate = new Date("08-03-2017UTC");
var startSunday = new Date(pickedDate);
startSunday.setDate(pickedDate.getDate() - pickedDate.getDay());
var startMonth = new Date(pickedDate);
startMonth.setDate(1);
var startDate = Math.max(startMonth,startSunday);
console.log("Start:" , new Date(startDate));
var endSaturday = new Date(pickedDate);
endSaturday.setDate(pickedDate.getDate() + (7-pickedDate.getDay()));
var endMonth = new Date(pickedDate);
endMonth.setMonth(pickedDate.getMonth()+1);//Add a month
endMonth.setDate(0);// to select last day of previous month.
var endDate = Math.min(endMonth,endSaturday);
console.log("End" , new Date(endDate));
The trick was to play with the dates, find all the possible start and end dates, then choose the right one with Math.min and Math.max which will compare the dates using their timestamp.
There is very good Library available in JavaScript to handle Date Manipulations.
https://github.com/datejs/Datejs
There is a method
Date.parse('next friday') // Returns the date of the next Friday.
Date.parse('last monday')
Using these method you can get the start and ending date of the week based on the current week.
I hope that it will help.
You can simply achieve this using the library moment. There are a lot of useful functions in this library.
var selectedDate = moment('Mon Aug 10 2017');
//If you want to get the ISO week format(Monday to Sunday)
var weekStart = selectedDate.clone().startOf('isoweek').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('isoweek').format('MMM Do');
//If you want to get the Sunday to Saturday week format
var weekStart = selectedDate.clone().startOf('week').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('week').format('MMM Do');
No need angular directive here, you could use the JavaScript extension which is below.
//get week from date
Date.prototype.getWeekNumber = function (weekstart) {
var target = new Date(this.valueOf());
// Set default for weekstart and clamp to useful range
if (weekstart === undefined) weekstart = 1;
weekstart %= 7;
// Replaced offset of (6) with (7 - weekstart)
var dayNr = (this.getDay() + 7 - weekstart) % 7;
target.setDate(target.getDate() - dayNr + 0);//0 means friday
var firstDay = target.valueOf();
target.setMonth(0, 1);
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstDay - target) / 604800000);;
};
//get date rance of week
Date.prototype.getDateRangeOfWeek = function (weekNo, weekstart) {
var d1 = this;
var firstDayOfWeek = eval(d1.getDay() - weekstart);
d1.setDate(d1.getDate() - firstDayOfWeek);
var weekNoToday = d1.getWeekNumber(weekstart);
var weeksInTheFuture = eval(weekNo - weekNoToday);
var date1 = angular.copy(d1);
date1.setDate(date1.getDate() + eval(7 * weeksInTheFuture));
if (d1.getFullYear() === date1.getFullYear()) {
d1.setDate(d1.getDate() + eval(7 * weeksInTheFuture));
}
var rangeIsFrom = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
d1.setDate(d1.getDate() + 6);
var rangeIsTo = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
return { startDate: rangeIsFrom, endDate: rangeIsTo }
};
Your code can be look like this
var startdate = '01-08-2017'
var weekList = [];
var year = startdate.getFullYear();
var onejan = new Date(year, 0, 1);//first january is the first week of the year
var weekstart = onejan.getDay();
weekNumber = startdate.getWeekNumber(weekstart);
//generate week number
var wkNumber = weekNumber;
var weekDateRange = onejan.getDateRangeOfWeek(wkNumber, weekstart);
var wk = {
value: wkNumber
, text: 'Week' + wkNumber.toString()
, weekStartDate: new Date(weekDateRange.startDate)
, weekEndDate: new Date(weekDateRange.endDate)
};
weekList.push(wk);
I guess there is no directive or filter for this, you need to create one for yourself. you can refer date object from date-time-object

How to get first and last day of current week when days are in different months?

For example, in the case of 03/27/2016 to 04/02/2016, the dates fall in different months.
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay();
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();
The getDay method returns the number of the day in the week, with Sunday as 0 and Saturday as 6. So if your week starts on Sunday, just subtract the current day number in days from the current date to get the start, and add 6 days get the end, e.g.
function getStartOfWeek(date) {
// Copy date if provided, or use current date if not
date = date? new Date(+date) : new Date();
date.setHours(0,0,0,0);
// Set date to previous Sunday
date.setDate(date.getDate() - date.getDay());
return date;
}
function getEndOfWeek(date) {
date = getStartOfWeek(date);
date.setDate(date.getDate() + 6);
return date;
}
document.write(getStartOfWeek());
document.write('<br>' + getEndOfWeek())
document.write('<br>' + getStartOfWeek(new Date(2016,2,27)))
document.write('<br>' + getEndOfWeek(new Date(2016,2,27)))
You can find below solution for your problem.
let currentDate = new Date; // get current date
let first = currentDate.getDate() - currentDate.getDay();
var last = first + 6; // last day is the first day + 6
let firstDayWeek = new Date(currentDate.setDate(first)).toISOString();
var lastDayWeek = new Date(currentDate.setDate(last)).toISOString();
console.log(firstDayWeek, "first Day in week")
console.log(lastDayWeek, "end Day in week")
I like the moment library for this kind of thing:
moment().startOf("week").toDate();
moment().endOf("week").toDate();
You can try this:
var currDate = new Date();
day = currDate.getDay();
first_day = new Date(currDate.getTime() - 60*60*24* day*1000);
last_day = new Date(currDate.getTime() + 60 * 60 *24 * 6 * 1000);

How to get year/month/day from a date object?

alert(dateObj) gives Wed Dec 30 2009 00:00:00 GMT+0800
How to get date in format 2009/12/30?
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
newdate = year + "/" + month + "/" + day;
or you can set new date and give the above values
new Date().toISOString()
"2016-02-18T23:59:48.039Z"
new Date().toISOString().split('T')[0];
"2016-02-18"
new Date().toISOString().replace('-', '/').split('T')[0].replace('-', '/');
"2016/02/18"
new Date().toLocaleString().split(',')[0]
"2/18/2016"
var dt = new Date();
dt.getFullYear() + "/" + (dt.getMonth() + 1) + "/" + dt.getDate();
Since month index are 0 based you have to increment it by 1.
Edit
For a complete list of date object functions see
Date
getMonth()
Returns the month (0-11) in the specified date according to local time.
getUTCMonth()
Returns the month (0-11) in the specified date according to universal time.
Why not using the method toISOString() with slice or simply toLocaleDateString()?
Beware that the timezone returned by toISOString is always zero UTC offset, whereas in toLocaleDateString it is the user agent's timezone.
Check here:
const d = new Date() // today, now
// Timezone zero UTC offset
console.log(d.toISOString().slice(0, 10)) // YYYY-MM-DD
// Timezone of User Agent
console.log(d.toLocaleDateString('en-CA')) // YYYY-MM-DD
console.log(d.toLocaleDateString('en-US')) // M/D/YYYY
console.log(d.toLocaleDateString('de-DE')) // D.M.YYYY
console.log(d.toLocaleDateString('pt-PT')) // DD/MM/YYYY
I would suggest you to use Moment.js http://momentjs.com/
Then you can do:
moment(new Date()).format("YYYY/MM/DD");
Note: you don't actualy need to add new Date() if you want the current TimeDate, I only added it as a reference that you can pass a date object to it. for the current TimeDate this also works:
moment().format("YYYY/MM/DD");
2021 ANSWER
You can use the native .toLocaleDateString() function which supports several useful params like locale (to select a format like MM/DD/YYYY or YYYY/MM/DD), timezone (to convert the date) and formats details options (eg: 1 vs 01 vs January).
Examples
new Date().toLocaleDateString() // 8/19/2020
new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 08/19/2020 (month and day with two digits)
new Date().toLocaleDateString('en-ZA'); // 2020/08/19 (year/month/day) notice the different locale
new Date().toLocaleDateString('en-CA'); // 2020-08-19 (year-month-day) notice the different locale
new Date().toLocaleString("en-US", {timeZone: "America/New_York"}); // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)
new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"}); // 09 (just the hour)
Notice that sometimes to output a date in your specific desire format, you have to find a compatible locale with that format.
You can find the locale examples here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all
Please notice that locale just change the format, if you want to transform a specific date to a specific country or city time equivalent then you need to use the timezone param.
var date = new Date().toLocaleDateString()
"12/30/2009"
info
If a 2 digit month and date is desired (2016/01/01 vs 2016/1/1)
code
var dateObj = new Date();
var month = ('0' + (dateObj.getMonth() + 1)).slice(-2);
var date = ('0' + dateObj.getDate()).slice(-2);
var year = dateObj.getFullYear();
var shortDate = year + '/' + month + '/' + date;
alert(shortDate);
output
2016/10/06
fiddle
https://jsfiddle.net/Hastig/1xuu7z7h/
credit
More info from and credit to this answer
more
To learn more about .slice the try it yourself editor at w3schools helped me understand better how to use it.
let dateObj = new Date();
let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());
For reference you can see the below details
new Date().getDate() // Return the day as a number (1-31)
new Date().getDay() // Return the weekday as a number (0-6)
new Date().getFullYear() // Return the four digit year (yyyy)
new Date().getHours() // Return the hour (0-23)
new Date().getMilliseconds() // Return the milliseconds (0-999)
new Date().getMinutes() // Return the minutes (0-59)
new Date().getMonth() // Return the month (0-11)
new Date().getSeconds() // Return the seconds (0-59)
new Date().getTime() // Return the time (milliseconds since January 1, 1970)
let dateObj = new Date();
let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());
console.log(myDate)
Use the Date get methods.
http://www.tizag.com/javascriptT/javascriptdate.php
http://www.htmlgoodies.com/beyond/javascript/article.php/3470841
var dateobj= new Date() ;
var month = dateobj.getMonth() + 1;
var day = dateobj.getDate() ;
var year = dateobj.getFullYear();
Nice formatting add-in: http://blog.stevenlevithan.com/archives/date-time-format.
With that you could write:
var now = new Date();
now.format("yyyy/mm/dd");
EUROPE (ENGLISH/SPANISH) FORMAT
I you need to get the current day too, you can use this one.
function getFormattedDate(today)
{
var week = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var day = week[today.getDay()];
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
var hour = today.getHours();
var minu = today.getMinutes();
if(dd<10) { dd='0'+dd }
if(mm<10) { mm='0'+mm }
if(minu<10){ minu='0'+minu }
return day+' - '+dd+'/'+mm+'/'+yyyy+' '+hour+':'+minu;
}
var date = new Date();
var text = getFormattedDate(date);
*For Spanish format, just translate the WEEK variable.
var week = new Array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado');
Output: Monday - 16/11/2015 14:24
With the accepted answer, January 1st would be displayed like this: 2017/1/1.
If you prefer 2017/01/01, you can use:
var dt = new Date();
var date = dt.getFullYear() + '/' + (((dt.getMonth() + 1) < 10) ? '0' : '') + (dt.getMonth() + 1) + '/' + ((dt.getDate() < 10) ? '0' : '') + dt.getDate();
Here is a cleaner way getting Year/Month/Day with template literals:
var date = new Date();
var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;
console.log(formattedDate);
It's Dynamic It will collect the language from user's browser setting
Use minutes and hour property in the option object to work with them..
You can use long value to represent month like Augest 23 etc...
function getDate(){
const now = new Date()
const option = {
day: 'numeric',
month: 'numeric',
year: 'numeric'
}
const local = navigator.language
labelDate.textContent = `${new
Intl.DateTimeFormat(local,option).format(now)}`
}
getDate()
You can simply use This one line code to get date in year-month-date format
var date = new Date().getFullYear() + "-" + new Date().getMonth() + 1 + "-" + new Date().getDate();
ES2018 introduced regex capture groups which you can use to catch day, month and year:
const REGEX = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})/;
const results = REGEX.exec('2018-07-12');
console.log(results.groups.year);
console.log(results.groups.month);
console.log(results.groups.day);
Advantage of this approach is possiblity to catch day, month, year for non-standard string date formats.
Ref. https://www.freecodecamp.org/news/es9-javascripts-state-of-art-in-2018-9a350643f29c/
One liner, using destructuring.
Makes 3 variables of type string:
const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-')
Makes 3 variables of type number (integer):
const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-').map(x => parseInt(x, 10))
From then, it's easy to combine them any way you like:
const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-');
const dateFormatted = `${year}/${month}/${day}`;
I am using this which works if you pass it a date obj or js timestamp:
getHumanReadableDate: function(date) {
if (date instanceof Date) {
return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
} else if (isFinite(date)) {//timestamp
var d = new Date();
d.setTime(date);
return this.getHumanReadableDate(d);
}
}

Categories