find tomorrow day, and the day after tomorrow in AS3 - actionscript-3

I've got this code :
var currentDate=new Date();
var my_date:Date = new Date();
var month=currentDate.getMonth()+1;
var day=currentDate.getDate();
var day2=currentDate.getDate()+1;
var day3=currentDate.getDate()+2;
var day4=currentDate.getDate()+3;
var day5=currentDate.getDate()+4;
var year=currentDate.getFullYear();
var tomorrow;
var three;
var four;
var five;
var months:Array = ["janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "decembre"];
var today =(day+" "+ months[my_date.month]);
var days:Array = ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"];
I'd like to have the day of tomorrow (and the 5 next ones).
I've tried :
tomorrow =(days[my_date.day+1]+" "+day2 +" "+ months[my_date.month]+" "+ year);
trace(tomorrow);
It's working. I've got "samedi 5 juillet 2015"
but then I've tried :
day3 =(days[my_date.day+2]+" "+day2 +" "+ months[my_date.month]+" "+ year);
trace(day3 );
But it results with "undefined 6 juillet 2015".
Do you know how I could do it ?
Thank you
EDIT
So I've add to my code for the name days:
var index:int = my_date.day + 2
if(index >= days.length)
{
index -= days.length;
}
So here's my code :
var currentDate=new Date();
var my_date:Date = new Date();
var month=currentDate.getMonth()+1;
var day=currentDate.getDate();
var day2=currentDate.getDate()+1;
var day3=currentDate.getDate()+2;
var year=currentDate.getFullYear();
var tomorrow;
var three;
var four;
var five;
var six;
var months:Array = ["janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "decembre"];
var days:Array = ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"];
var today =(days[my_date.day]+" "+day +" "+ months[my_date.month]+" "+ year);
var index:int = my_date.day + 2
if(index >= days.length)
{
index -= days.length;
}
trace(days[index+6]);
I've add these lines for sunday has the were a bug (saturday was "undefined") :
if(days[index] == "dimanche"){
tomorrow =(days[index+6]+" "+day2 +" "+ months[my_date.month]+" "+ year);
}else{
tomorrow =(days[index-1]+" "+day2 +" "+ months[my_date.month]+" "+ year);
}
And then
three = (days[index] + " " + day3 + " " + months[my_date.month] + " " + year);
four = (days[index+1] + " " + day4 + " " + months[my_date.month] + " " + year);
five = (days[index+2] + " " + day3 + " " + months[my_date.month] + " " + year);
}
But it seems that it doesn't work with all days.
For the "third july', it's working great :
But if I change the computer date and choose, for exemple, the 23d of July
Some days are "undefined".
Any idea why ?

The problem appears to be index-related. You're trying to access days[my_date.day+2], which (depending on the day) may refer to an index out of bounds. If my_date.day + 1 or my_date.day + 2 is ever greater than days.length, you'll encounter the same issue.
You can solve this with a simple condition. For example, if my_date.day + 2 is greater than or equal to days.length, access days[my_date.day + 2 - days.length] instead. This ensures what we're calling is within bounds.
Example:
var index:int = my_date.day + 2
if(index >= days.length)
{
index %= days.length;
}
day3 = (days[index] + " " + day2 + " " + months[my_date.month] + " " + year);
trace(day3);
This should fix your issue. Hope it helps!

To show future dates using months and days arrays, you can do like this :
var months:Array = ['janvier', 'fevrier', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'decembre'],
days:Array = ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'];
function show_7_days(date:Date): void {
var future_date:Date = new Date(date.fullYear, date.month, date.date);
for(var i:int = 1; i < 8; i++){
future_date.date = date.date + i;
trace(
days[future_date.getDay()] + ' '
+ future_date.getDate() + ' '
+ months[future_date.getMonth()] + ' '
+ future_date.getFullYear()
);
}
}
And then :
show_7_days(new Date());
// gives :
// samedi 4 juillet 2015
// dimanche 5 juillet 2015
// lundi 6 juillet 2015
// mardi 7 juillet 2015
// mercredi 8 juillet 2015
// jeudi 9 juillet 2015
// vendredi 10 juillet 2015
And for a specific date :
show_7_days(new Date(1900, 3, 3));
// gives :
// mercredi 4 avril 1900
// jeudi 5 avril 1900
// vendredi 6 avril 1900
// samedi 7 avril 1900
// dimanche 8 avril 1900
// lundi 9 avril 1900
// mardi 10 avril 1900
But you can also simplify things using a flash.globalization.DateTimeFormatter like this :
var date_formater:DateTimeFormatter = new DateTimeFormatter('fr-FR', DateTimeStyle.LONG, DateTimeStyle.NONE);
function show_7_days(date:Date): void {
var future_date:Date = new Date(date.fullYear, date.month, date.date);
for(var i:int = 1; i < 8; i++){
future_date.date = date.date + i;
trace(date_formater.format(future_date));
}
}
Which will give you the same results.
Hope that can help.

Related

Google Sheets getDay() Shows an Incorrect Value

Date() shows the correct date while getDay() shows an incorrect value.
function Test()
{
const date = new Date();
const dateToday = Utilities.formatDate(new Date(), "GMT+8", "MM/dd/YYYY");
const dateYesterday = Utilities.formatDate(new Date(new Date().setDate(date.getDate() - 1)), "GMT+8", "MM/dd/YYYY");
var day = date.getDay();
var a = SpreadsheetApp.getActiveSheet().getRange(3, 2);
switch (day)
{
case 1:
day = "Sunday";
break;
case 2:
day = "Monday";
break;
case 3:
day = "Tuesday";
break;
case 4:
day = "Wednesday";
break;
case 5:
day = "Thursday";
break;
case 6:
day = "Friday";
break;
case 7:
day = "Saturday";
}
a.setValue("Today is " + day + " " + dateToday + ". Yesterday was " + dateYesterday);
}
When this code was executed in Google Sheet, it will output below:
Today is Tuesday 04/21/2022. Yesterday was 04/20/2022
The dates are correct while the day shows Tuesday which is incorrect. It's Thursday right now.
As another approach, in your situation, how about the following modification?
Modified script:
function sample() {
const date = new Date();
const dateToday = Utilities.formatDate(new Date(), "GMT+8", "MM/dd/YYYY");
const dateYesterday = Utilities.formatDate(new Date(new Date().setDate(date.getDate() - 1)), "GMT+8", "MM/dd/YYYY");
const day = Utilities.formatDate(new Date(), "GMT+8", "EEEE"); // Added
const a = SpreadsheetApp.getActiveSheet().getRange(3, 2);
a.setValue("Today is " + day + " " + dateToday + ". Yesterday was " + dateYesterday);
}
In this modification, the day name is retrieved using Utilities.formatDate like Utilities.formatDate(new Date(), "GMT+8", "EEEE").
Reference:
formatDate(date, timeZone, format)
The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.
Sunday is 0, Monday is 1, etc.
docs
And example with a less length implementation:
const getDayofWeek = x => x === 0 ? 'Sunday' : x === 1 ? 'Monday' : x === 2 ? 'Tuesday' : x === 3 ? 'Wednesday' : x === 4 ? 'Thursday' : x === 5 ? 'Friday' : x === 6 ? 'Saturday' : "Invalid Day";
for (i = 0; i < 8; i++) {
console.log(getDayofWeek(i))
}
Try
function test() {
const dayOfTheWeek = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
const date = new Date();
console.log(dayOfTheWeek[date.getDay()])
}
const dayOfTheWeek = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
const date = new Date();
console.log(dayOfTheWeek[date.getDay()])
The most important thing is to check your timezone in your script editor : go to your script editor, ckick on the gear on the left hand side, check the third box, go back to script editor and review in appsscript.json, hange timezone according to your locale
Try it this way:
function Test() {
const dt = new Date();
const dateToday = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "MM/dd/yyyy");
const dateYesterday = Utilities.formatDate(new Date(dt.getFullYear(), dt.getMonth(), dt.getDate() - 1), Session.getScriptTimeZone(), "MM/dd/yyyy");
var d = dt.getDay();
var a = SpreadsheetApp.getActiveSheet().getRange(3, 2);
var day;
switch (d) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
Logger.log("Today is " + day + " " + dateToday + ". Yesterday was " + dateYesterday)
a.setValue("Today is " + day + " " + dateToday + ". Yesterday was " + dateYesterday);
}

Date Bookmarklet not working in chrome

Below is a bookmarklet that is not working can someone help me out.
javascript:function url() {
var date = new Date();
date.setDate(date.getDate() + (1 + 7 - date.getDay()) % 7);
var y = date.getFullYear();
var m = date.getMonth() +1;
if(m < 10){m = '0' + m;}
var d = date.getDate();
if(d < 10){d = '0' + d;}
var date = y + "-" + m + "-" + d;
return 'https://wms.blueapron.com/facilities/4/grocery-board?view_type=cumulative&week_starts_on=' + date
}window.open(url(),"_blank");
The working bookmarklet may look like this:
javascript:(function() {
window.open(url(),"_blank");
function url() {
var date = new Date();
date.setDate(date.getDate() + ((8 - date.getDay()) % 7 ? (8 - date.getDay()) % 7 : 7));
var y = date.getFullYear();
var m = date.getMonth() +1;
if(m < 10){m = '0' + m;}
var d = date.getDate();
if(d < 10){d = '0' + d;}
var date = y + "-" + m + "-" + d;
return 'https://wms.blueapron.com/facilities/4/grocery-board?view_type=cumulative&week_starts_on=' + date;
}
})();

Google Apps Script to remove hangouts links from calendar events

I have successfully accessed a Google calendar event and can change the color, but I'm stuck when it comes to removing the hangouts link.
I'm attempting to use code to automatically remove the hangouts links when I am the meeting originator and have not changed the hangout name, but I'm not having any success in actually changing the link.
Any help greatly appreciated.
function removehangout() {
var calendarId = 'primary';
//var calendars = CalendarApp.getOwnedCalendarsByName('Mirage ELDRIDGE');
var now = new Date();
// Determines how many events are happening in the next 24 hours x 1 days.
var now = new Date();
var endr = new Date(now.getTime() + (1 * 24 * 60 * 60 * 1000));
var events2 = CalendarApp.getDefaultCalendar().getEvents(now, endr);
Logger.log('Number of events: ' + events2.length);
var events = Calendar.Events.list(calendarId, {
timeMin: now.toISOString(),
singleEvents: true,
orderBy: 'startTime',
maxResults: 5
});
if (events.items && events.items.length > 0) {
for (var i = 0; i < events.items.length; i++) {
var event1 = events.items[i];
var d = event1.description;
var ttitle = event1.summary;
var whoby = event1.creator.email;
Logger.log(ttitle + ' by: ' + whoby);
if(whoby.indexOf('mirage.eldridge') != -1){
Logger.log(ttitle + '--> was by mirage');
var hangoutname = event1.hangoutLink;
Logger.log(ttitle + '--> hangout link name --> ' + hangoutname);
if (hangoutname != null) {
if (hangoutname.indexOf('mirage-eldridge') != -1){
//delete this link here
Logger.log(ttitle + '--> remove hangout');
//event.setHangoutLink(null);
//var idno = event.iCalUID
//CalendarApp.getEventSeriesById(idno)
event1.HangoutLink = null;
Logger.log(ttitle + '... ' + event1.hangoutLink);
Logger.log(event1.iCalUID);
//event.setcolorId('11');
var event2 = Calendar.Events.get(calendarId, event1.id)
event2.colorId = 9;
event2.hangoutLink = 'fred';
//Calendar.Events.patch(event2,calendarId,event1.id);
Calendar.Events.update(event2,calendarId,event1.id);
}
} else {
Logger.log(ttitle + ' -- do not remove ' + hangoutname);
}
}
if (!d)
d = '';
//var foundlinkyes = d.indexOf('HangoutLink');
//var actuallink = event.hangoutLink;
//var hasrlink = 'True';
//if (!actuallink) {
//Logger.log(ttitle + ' no link found');
//hasrlink = "False";
//}
//Logger.log('desc: ' + ttitle + '-- foundyes: ' + foundlinkyes);
//if (foundlinkyes == -1 && hasrlink == 'True'){
//if (event.hangoutLink && (d.indexOf('Hangout: ')== -1)){
//Logger.log (event.summary + ' - ' + event.hangoutLink + ' - ' + event.description);
//Logger.log(ttitle + ' added this ' + event.hangoutLink);
//event.description = 'HangoutLink: ' + event.hangoutLink + '\n\n' + d;
//Calendar.Events.update(event, calendarId, event.id);
//foundlinkyes = 0;
//hasrlink = 'True';
//}
//}
}
} else {
Logger.log('No events found.');
}
}

html5 date: how to get date as yyyy-mm-ddTH:i:s+Z format in javascript

I am trying to get the date using html5 date type,and it is used for an api call with some parameters,but i will get the following error message from api.
date field must be yyyy-mm-ddTH:i:s+Z
I wll read the date as this format
Sun Jun 12 2016 00:00:00 GMT+0530 (India Standard Time)
So how can i convert the above date into yyyy-mm-ddTH:i:s+Z format?
Note:
I am using javascript
UPDATE
I am used toISOString() method but it didn't worked
It's very easy to use momentjs...
Please, check my fiddle
var time = 'Sun Jun 12 2016 00:00:00 GMT+0530';
time = moment(time).format("YYYY-MM-DDThh:mm:ssZ");
$('.time').text(time);
Hope this helps!
I hope this is what you wanted:
function getTimeZone(date) {
var offset = date.getTimezoneOffset(),
o = Math.abs(offset);
return (offset < 0 ? "+" : "-") + ("00" + Math.floor(o / 60)).slice(-2) + ":" + ("00" + (o % 60)).slice(-2);
}
function getFormattedDate(date) {
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
var hours = date.getHours();
var mins = date.getMinutes();
var sec = date.getSeconds();
var timeZone = getTimeZone(date);
return year + '-' + month + '-' + day + ' ' + hours + ':' + mins + ':' + sec + ' ' + timeZone;
}
document.write(getFormattedDate(new Date()));
This will print: 2016-5-2 19:54:59 +06:00
JsFiddle link: https://jsfiddle.net/sktajbir/pmbdk33L/2/
FYI, getTimeZone() function is taken from here.
Thanks.

HTML5 Input datetime-local default value of today and current time

Is there anyway that I can make a default value of HTML5 input type='datetime-local' to today's date and this current time.
Thanks before
You can make it shorter:
<input type="datetime-local" id="cal">
window.addEventListener('load', () => {
var now = new Date();
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
/* remove second/millisecond if needed - credit ref. https://stackoverflow.com/questions/24468518/html5-input-datetime-local-default-value-of-today-and-current-time#comment112871765_60884408 */
now.setMilliseconds(null)
now.setSeconds(null)
document.getElementById('cal').value = now.toISOString().slice(0, -1);
});
It's possible. By using a JQuery function, you can have a really complete solution.
Here is an example.
JSFiddle http://jsfiddle.net/v8MNx/1/
HTML
<form action="demo.html" id="myForm">
<p>
<label>Date:</label>
<input type="datetime" name="anniversaire" id="anniversaire"/>
</p>
<input type="submit" value="Submit"/>
</form>
JQuery:
//Function found here: https://gist.github.com/ryanburnette/8803238
$.fn.setNow = function (onlyBlank) {
var now = new Date($.now())
, year
, month
, date
, hours
, minutes
, seconds
, formattedDateTime
;
year = now.getFullYear();
month = now.getMonth().toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;
date = now.getDate().toString().length === 1 ? '0' + (now.getDate()).toString() : now.getDate();
hours = now.getHours().toString().length === 1 ? '0' + now.getHours().toString() : now.getHours();
minutes = now.getMinutes().toString().length === 1 ? '0' + now.getMinutes().toString() : now.getMinutes();
seconds = now.getSeconds().toString().length === 1 ? '0' + now.getSeconds().toString() : now.getSeconds();
formattedDateTime = year + '-' + month + '-' + date + 'T' + hours + ':' + minutes + ':' + seconds;
if ( onlyBlank === true && $(this).val() ) {
return this;
}
$(this).val(formattedDateTime);
return this;
}
$(function () {
// Handler for .ready() called.
$('input[type="datetime"]').setNow();
});
The accepted answer seems pretty complicated to me... here a shorter solution that doesn't need jQuery
JSFiddle: https://jsfiddle.net/rzaceg8v/
window.addEventListener("load", function() {
var now = new Date();
var utcString = now.toISOString().substring(0,19);
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var localDatetime = year + "-" +
(month < 10 ? "0" + month.toString() : month) + "-" +
(day < 10 ? "0" + day.toString() : day) + "T" +
(hour < 10 ? "0" + hour.toString() : hour) + ":" +
(minute < 10 ? "0" + minute.toString() : minute) +
utcString.substring(16,19);
var datetimeField = document.getElementById("myDatetimeField");
datetimeField.value = localDatetime;
});
<input type="datetime-local" id="myDatetimeField"/>
The methods above worked but were too verbose for me.
Here's my version:
window.addEventListener("load", function() {
var now = new Date();
var offset = now.getTimezoneOffset() * 60000;
var adjustedDate = new Date(now.getTime() - offset);
var formattedDate = adjustedDate.toISOString().substring(0,16); // For minute precision
var datetimeField = document.getElementById("myDatetimeField");
datetimeField.value = formattedDate;
});
This worked perfectly!
One note, I tried this the only month it would break, October. It would give me a '010', instead of 10.
month = (now.getMonth() +1 ).toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1;
Big line works for me, if it doesn't for you you can introduce whitespaces and line breaks in the expressions.
function setDatetimeInput(element, t = new Date()){
function p(number){return number.toString().padStart(2, '0');}//number to 2 digit, 0 padded string
element.value = `${t.getFullYear()}-${p(t.getMonth()+1)}-${p(t.getDate())}T${p(t.getHours())}:${p(t.getMinutes())}`;
}
here's a simple way:
<input type="datetime-local" id="cal">
const currentDateTime = () => {
var tzoffset = new Date().getTimezoneOffset() * 60000; //offset in milliseconds
var localISOString = new Date(Date.now() - tzoffset)
.toISOString()
.slice(0, -1);
// convert to YYYY-MM-DDTHH:MM
const datetimeInputString = localISOString.substring(
0,
((localISOString.indexOf("T") | 0) + 6) | 0
);
console.log(datetimeInputString);
return datetimeInputString;
};
document.getElementById('cal').value = currentDateTime();