I am trying to figure out the 1st date and last date of the current week as well as the 1st date and last date of the current month in the format yyyy-mm-dd using Google App scripts. Date() seems to be a difficult object for me, therefore seeking advice. Please consider Saturday is the starting day and Friday is the end day of a week in this parts of the world.
Get first (Saturday) and last (Friday) date of this week
You can use Date.getDay() to get the current day of the week (0=Sunday, 1=Monday, etc.). But there is no method Date.setDay() so we need to do a little math to figure out how many days ago the most recent Saturday was, and use Date.setDate():
// Get the Date for the Saturday on or preceding the current date.
var saturday = new Date(); // Today
var day = date.getDay(); // Day of week (0-6)
var newDay = date.getDate() - ((day + 1) % 7); // The day of the month we want.
saturday.setDate(newDay); // Our date object for Saturday.
(day + 1) % 7 calculates how many days to subtract; for example, if today is Sunday (day=0), we need to go back one day: (0 + 1) % 7 = 1. But if today is Saturday (day=6), we get (6 + 1) % 7 = 0 and we don't subtract any days.
The routine for finding the upcoming Friday is similar, but we add days instead of subtracting:
// Get the Date for the Friday on or after the given date.
var friday = new Date(date); // today
var day = date.getDay();
var diff = date.getDate() + ((5 - day) % 7);
friday.setDate(diff);
Get first and last date of this month
This is simpler using setDate(), since it takes as its parameter the day of the month.
var firstOfMonth = new Date(); // today
firstOfMonth.setDate(1); // Sets the day to the first of the month
To get the last of the month, we go ahead one month, then back to the last day of the previous month (the last of this month):
var lastOfMonth = new Date();
lastOfMonth.setMonth(lastOfMonth.getMonth()+1); // Go ahead one month
lastOfMonth.setDate(0); // Sets to 1 day before the first of the month, i.e. the last of this month.
Convert to format 'yyyy-mm-dd'
Google Apps Script has a built-in method for formatting dates: Utilities.formatDate(date, timezone, format)
date is a Date object, timezone is a string such as those from the TZ database, and format is a string in SimpleDateFormat
For example:
var formattedDate = Utilities.formatDate(friday, 'America/Denver', 'yyyy-MM-dd');
(Note the capital MM for month because mm represents minutes.)
You can use toLocaleString("sv-SE") to convert the date to the desired format yyyy-mm-dd.
Try this:
const today = new Date();
const firstWeekD = today.getDate() - today.getDay()-1;
const lastWeekD = firstWeekD + 6;
const firstdayOfWeek = new Date(today.setDate(firstWeekD)).toLocaleString("sv-SE").slice(0,10);
const lastdayOfWeek = new Date(today.setDate(lastWeekD)).toLocaleString("sv-SE").slice(0,10);
const date = new Date();
const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1).toLocaleString("sv-SE").slice(0,10);
const lastDayOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0).toLocaleString("sv-SE").slice(0,10);
console.log(firstdayOfWeek); // first day of the week - Saturday
console.log(lastdayOfWeek); // last day of the week - Friday
console.log(firstDayOfMonth) // first day of the month
console.log(lastDayOfMonth) // last day of the month
Using this function in momentjs I can find the week number of the year:
var dt = new Date();
var weekNumber = moment(dt).week();
Can anyone tell me how to set the first week in April as week one, and therefore for week 52 to be the last week in March.
In the documentation I can only see how to adjust the first day of the year (ie Sunday or Monday). I need to do both. Saturday will actually be day one.
Help much appreciated.
You will have to add a custom function,
Sample
function getCustomWeekNumber(weekNo) {
var baseWeek = moment("01/04/", "DD/MM/").week() - 1; // 13
var lastWeek = moment("31/12/", "DD/MM/").week() //53;
return weekNo > baseWeek ? weekNo - baseWeek : (lastWeek - baseWeek) + weekNo;
}
var d = moment().week();
console.log(getCustomWeekNumber(d))
d = moment("01/04/2016", "DD/MM/YYYY").week();
console.log(getCustomWeekNumber(d))
d = moment("24/03/2016", "DD/MM/YYYY").week();
console.log(getCustomWeekNumber(d))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.0/moment.min.js"></script>
i am looking to display the date plus 1 month inside a div which will be used to display next invoice date. i have seen a few examples in various places, but could not implement. I also saw that there were many solutions, and some controversy surrounding each one.
Once you have a date object, just call setMonth(), passing in the current number of months plus 1.
var CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth() + 1);
You can either use this : http://jsfiddle.net/dfA8b/ if you need same date of the next month
var invoiceDt = new Date();
invoiceDt.setMonth(invoiceDt.getMonth()+1);
$('#invoiceDate').text(invoiceDt.toDateString());
Or
You can use this : http://jsfiddle.net/hjSDu/ if you need 30 days month(mostly used for invoice purposes)
var invoiceDt = new Date();
var days = 30;
invoiceDt.setDate(invoiceDt.getDate()+days);
$('#invoiceDate').text(invoiceDt.toDateString());
For the formatting purpose :
http://jsfiddle.net/7bU6n/
var invoiceDt = new Date();
invoiceDt.setMonth(invoiceDt.getMonth()+1);
$('#invoiceDate').text((invoiceDt.getMonth()+1) +"-"+ invoiceDt.getDate() +"-" + invoiceDt.getFullYear());
also see : https://stackoverflow.com/a/1643468/3603806
1 month is not so clear... what You mean? 31, 30 days or if exists simply same date of the following month?
1st case: (assuming 31 days)
var d = new Date(),
dplus31 = d.getDate() + 31;
d.setDate(dplus31);
console.debug(d, dplus31);
2nd case: one month
var d = new Date(),
dplus1 = d.getMonth() + 1;
d.setMonth(dplus1);
console.debug(d, dplus1);
..but even in this case there are some edge cases (ex. 31 January)
hope it helps
function addMonthsNoOverflow(dateParam, intParam) {
var sum = new Date(new Date(dateParam.getTime()).setMonth(dateParam.getMonth() + intParam);
if (sum.getDate() < dateParam.getDate()) { sum.setDate(0); }
return(sum);
}
Notes:
It handles cases where 29, 30 or 31 turned into 1, 2, or 3 by eliminating the overflow
Day of Month is NOT zero-indexed so .setDate(0) is last day of prior month.
Total newbie at JavaScript.
I would like to calculate how many days one has been alive by asking the user their date of birth via prompts/alerts, then obviously subtracting their date of birth from today's date.
I've made a bit of a start...
var month=prompt("Please enter month of birth"," ");
var day=prompt("Please enter day of birth"," ");
var year=prompt("Please enter your year of birth"," ");
var curdate = this is the bit i need help with
var birth = this is the bit i need help with
var milliDay = 1000 * 60 * 60 * 24; // a day in milliseconds;
var ageInDays = (curdate - birth) / milliDay;
document.write("You have been alive for: " + ageInDays);
Any advice or help would be much appreciated.
You need to use the Date object (MDN). They can be created from a month, a day, and a year, and added/subtracted.
Typically :
var curDate = new Date();
var birth = new Date(year, month, day);
var ageInDays = (curdate.getTime() - birth.getTime()) / milliDay;
Be aware of the fact that months starts at 0, e.g. January is 0.
var curDate = new Date();
gives you the current date.
var birthdate = new Date(year, month-1, day);
gives you a Date from the separate variables. NB the month is zero-based.
end = Date.now(); // Get current time in milliseconds from 1 Jan 1970
var date = 20; //Date you got from the user
var month = 8-1; // Month, subtracted by one because month starts from 0 according to JS
var year = 1996; // Year
//Set date to the old time
obj = new Date();
obj.setDate(date);
obj.setMonth(month);
obj.setYear(year);
obj = obj.getTime(); //Get old time in milliseconds from Jan 1 1970
document.write((end-obj)/(1000*60*60*24));
Simply subtract current time from Jan 1 1970 in milliseconds from their birthdate's time from Jan 1 1970 in milliseconds. Then convert it to days. Look at MDN's Docs for more info.
See JSFiddle for a working example. Try entering yesterday's date. It should show 1 day.
Read some of this: http://www.w3schools.com/js/js_obj_date.asp
I've been using Javascript's Date for a project, but noticed today that my code that previously worked is no longer working correctly. Instead of producing Feb as expected, the code below produces March.
My code looks something like this:
current = new Date();
current.setMonth(current.getMonth()+1); //If today is Jan, expect it to be Feb now
This code worked everyday up until today. Is this a Javascript bug or am I going about this the wrong way?
You'll probably find you're setting the date to Feb 31, 2009 (if today is Jan 31) and Javascript automagically rolls that into the early part of March.
Check the day of the month, I'd expect it to be 1, 2 or 3. If it's not the same as before you added a month, roll back by one day until the month changes again.
That way, the day "last day of Jan" becomes "last day of Feb".
EDIT:
Ronald, based on your comments to other answers, you might want to steer clear of edge-case behavior such as "what happens when I try to make Feb 30" or "what happens when I try to make 2009/13/07 (yyyy/mm/dd)" (that last one might still be a problem even for my solution, so you should test it).
Instead, I would explicitly code for the possibilities. Since you don't care about the day of the month (you just want the year and month to be correct for next month), something like this should suffice:
var now = new Date();
if (now.getMonth() == 11) {
var current = new Date(now.getFullYear() + 1, 0, 1);
} else {
var current = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}
That gives you Jan 1 the following year for any day in December and the first day of the following month for any other day. More code, I know, but I've long since grown tired of coding tricks for efficiency, preferring readability unless there's a clear requirement to do otherwise.
Instead, try:
var now = new Date();
current = new Date(now.getFullYear(), now.getMonth()+1, 1);
I was looking for a simple one-line solution to get the next month via math so I wouldn't have to look up the javascript date functions (mental laziness on my part). Quite strangely, I didn't find one here.
I overcame my brief bout of laziness, wrote one, and decided to share!
Solution:
(new Date().getMonth()+1)%12 + 1
Just to be clear why this works, let me break down the magic!
It gets the current month (which is in 0..11 format), increments by 1 for the next month, and wraps it to a boundary of 12 via modulus (11%12==11; 12%12==0). This returns the next month in the same 0..11 format, so converting to a format Date() will recognize (1..12) is easy: simply add 1 again.
Proof of concept:
> for(var m=0;m<=11;m++) { console.info( "next month for %i: %i", m+1, (m+1)%12 + 1 ) }
next month for 1: 2
next month for 2: 3
next month for 3: 4
next month for 4: 5
next month for 5: 6
next month for 6: 7
next month for 7: 8
next month for 8: 9
next month for 9: 10
next month for 10: 11
next month for 11: 12
next month for 12: 1
So there you have it.
You can use the date.js library:
http://code.google.com/p/datejs/
And just do this
Date.today().next().month();
You will have the exact value for today + 1 month (including days)
If you use moment.js, they have an add function.
Here's the link -
https://momentjs.com/docs/#/manipulating/add/
moment().add(7, 'months');
I also wrote a recursive function based on paxdiablo's answer to add a variable number of months. By default this function would add a month to the current date.
function addMonths(after = 1, now = new Date()) {
var current;
if (now.getMonth() == 11) {
current = new Date(now.getFullYear() + 1, 0, 1);
} else {
current = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}
return (after == 1) ? current : addMonths(after - 1, new Date(now.getFullYear(), now.getMonth() + 1, 1))
}
Example
console.log('Add 3 months to November', addMonths(3, new Date(2017, 10, 27)))
Output -
Add 3 months to November Thu Feb 01 2018 00:00:00 GMT-0800 (Pacific Standard Time)
If you are able to get your hands on date-fns library v2+, you can import the function addMonths, and use that to get the next month
<script type="module">
import { addMonths } from 'https://cdn.jsdelivr.net/npm/date-fns/+esm';
const nextMonth = addMonths(new Date(), 1);
console.log(`Next month is ${nextMonth}`);
</script>
ah, the beauty of ternaries:
const now = new Date();
const expiry = now.getMonth() == 11 ? new Date(now.getFullYear()+1, 0 , 1) : new Date(now.getFullYear(), now.getMonth() + 1, 1);
just a simpler version of the solution provided by #paxdiablo and #Tom
try this:
var a = screen.Data.getFullYear();
var m = screen.Data.getMonth();
var d = screen.Data.getDate();
m = m + 1;
screen.Data = new Date(a, m, d);
if (screen.Data.getDate() != d)
screen.Data = new Date(a, m + 1, 0);
You may probably do this way
var currentMonth = new Date().getMonth();
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
for(var i = currentMonth-1 ; i<= 4; i++){
console.log(monthNames[i])// make it as an array of objects here
}
here is how i do it:
getMonthName(offset=0, format="long"){
/*
i.e.
offset: 0 - this month
offset: -1 - previous month
offset: 1 - next month
format: short - Oct
format: long - October
*/
const now = new Date();
const month = new Date(now.getFullYear(), now.getMonth() + offset, 1)
return month.toLocaleString('default', { month: format })
}