In google apps script I use often in summertimeperiod GMT+2 or in wintertime GMT+1 for the correct date.
To avoid to change this twice a year manually i developped following function:
function StartSummerWintertime() {
var i;
var today;
var year;
var SST;
var SWT;
var day;
var GMT_time;
today = new Date();
Logger.log("today = " + today)
year = today.getFullYear();
//Summertime starts last Sunday in March.
for (i = 31; i > 24; i--) {
SST = new Date("March " + i + "," + year);
day = SST.getDay();
if (day == 0) {
break;
}
}
Logger.log("Start date Summertime "+year+" = " + SST)
//Wintertime starts last Sunday in October.
for (i = 31; i > 24; i--) {
SWT = new Date("Oct " + i + "," + year);
day = SWT.getDay();
if (day == 0) {
break;
}
}
Logger.log("Start date Wintertime "+year+" = " + SWT)
//The switch takes place at 2:00 AM, so I have added 2 hours (= 2 * 60 * 60 * 1000 ms)
if (today.getTime() < (SST.getTime() + 2*60*60*1000) || today.getTime() > SWT.getTime() + (2*60*60*1000)) {
GMT_time = "GMT+1";
}
else {
GMT_time = "GMT+2";
}
Logger.log("GMT_time = " + GMT_time)
var date1 = Utilities.formatDate(new Date("July 6, 2021"), "GMT+2", "d-M-yyyy");
var date2 = Utilities.formatDate(new Date("July 6, 2021"), "GMT+1", "d-M-yyyy");
Logger.log("date1 = " + date1)
Logger.log("date2 = " + date2)
var date3 = Utilities.formatDate(new Date("July 6, 2021"), GMT_time, "d-M-yyyy");
var date4 = Utilities.formatDate(new Date("July 6, 2021"), GMT_time, "d-M-yyyy");
Logger.log("date3 = " + date3)
Logger.log("date4 = " + date4)
}
Date 1 and date 2 give different dates, date 3 and date 4 give correct (same) dates. The problem is solved however there should be a smarter (shorter) way to do so.
Please advise.
Related
I am facing some issue while calculating the time difference between two dates using the JavaScript. I am providing my code below.
Here I have cutoff time and dep_time value. I have to calculate today's date with dep_date and if today's date and time is before the cutoff time then it will return true otherwise false. In my case its working fine in Chrome but for same function it's not working in Firefox. I need it to work for all browsers.
function checkform() {
var dep_date = $("#dep_date1").val(); //07/27/2019
var cut_offtime = $("#cutoff_time").val(); //1
var dep_time = $("#dep_time").val(); //6:00pm
var dep_time1 = dep_time.replace(/[ap]/, " $&");
var todayDate = new Date();
var todayMonth = todayDate.getMonth() + 1;
var todayDay = todayDate.getDate();
var todayYear = todayDate.getFullYear();
if (todayDay < 10) {
todayDay = "0" + todayDay;
}
if (todayMonth < 10) {
todayMonth = "0" + todayMonth;
}
//console.log('both dates',todayMonth,todayDay,todayYear);
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(dep_date.replace(/\//g, " "));
var todayToDate = Date.parse(todayDateText.replace(/-/g, " "));
console.log("both dates", dep_date, todayDateText);
if (inputToDate >= todayToDate) {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? "pm" : "am";
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
var strTime = hours + ":" + minutes + " " + ampm;
var timeStart = new Date(todayDateText + " " + strTime);
var timeEnd = new Date(dep_date + " " + dep_time1);
var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds
var minutes = diff % 60;
var hours = (diff - minutes) / 60;
console.log("hr", hours);
if (parseInt(hours) > parseInt(cut_offtime)) {
return true;
} else {
alert("You should book this trip before " + cut_offtime + " hr");
return false;
}
} else {
alert("You should book this trip before " + cut_offtime + " hr");
return false;
}
}
Part of your issue is here:
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(dep_date.replace(/\//g, " "));
The first line generates a string like "07-17-2019". The next changes it to "07 17 2019" and gives it to the built–in parser. That string is not a format supported by ECMA-262 so parsing is implementation dependent.
Chrome and Firefox return a date for 17 July 2019, Safari returns an invalid date.
It doesn't make sense to parse a string to get the values, then generate another string to be parsed by the built–in parser. Just give the first set of values directly to the Date constructor:
var inputToDate = new Date(todayYear, todayMonth - 1, todayDay);
which will work in every browser that ever supported ECMAScript.
Similarly:
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? "pm" : "am";
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
var strTime = hours + ":" + minutes + " " + ampm;
var timeStart = new Date(todayDateText + " " + strTime);
appears to be a lengthy and brittle way to copy a date and set the seconds and milliseconds to zero. The following does exactly that in somewhat less code:
var date = new Date();
var timeStart = new Date(date);
timeStart.setMinutes(0,0);
use
var timeStart = new Date(todayDateText + " " + strTime)
Applying these changes to your code gives something like:
function parseMDY(s) {
var b = s.split(/\D/);
return new Date(b[2], b[0]-1, b[1]);
}
function formatDate(d) {
return d.toLocaleString(undefined, {
day: 'numeric',
month: 'short',
year: 'numeric'
});
}
// Call function with values
function checkform(dep_date, cut_offtime, dep_time) {
// Helper
function z(n) {
return (n<10?'0':'') + n;
}
// Convert dep_date to Date
var depD = parseMDY(dep_date);
// Get the departure time parts
var dtBits = dep_time.toLowerCase().match(/\d+|[a-z]+/gi);
var depHr = +dtBits[0] + (dtBits[2] == 'pm'? 12 : 0);
var depMin = +dtBits[1];
// Set the cutoff date and time
var cutD = new Date(depD);
cutD.setHours(depHr, depMin, 0, 0);
// Get current date and time
var now = new Date();
// Create cutoff string
var cutHr = cutD.getHours();
var cutAP = cutHr > 11? 'pm' : 'am';
cutHr = z(cutHr % 12 || 12);
cutMin = z(cutD.getMinutes());
var cutStr = cutHr + ':' + cutMin + ' ' + cutAP;
var cutDStr = formatDate(cutD);
// If before cutoff, OK
if (now < cutD) {
alert('Book before ' + cutStr + ' on ' + cutDStr);
return true;
// If after cutoff, not OK
} else {
alert('You should have booked before ' + cutStr + ' on ' + cutDStr);
return false;
}
}
// Samples
checkform('07/27/2019','1','6:00pm');
checkform('07/17/2019','1','11:00pm');
checkform('07/07/2019','1','6:00pm');
That refactors your code somewhat, but hopefully shows how to improve it and fix the parsing errors.
I always have problems figuring out dates functions
var d = new Date(),
month = d.getMonth(),
mondays = [];
d.setDate(1);
// Get the first Monday in the month
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getMonth() === month) {
var pushDate = new Date(d.getTime());
mondays.push(pushDate.getDate() + '-' + (pushDate.getMonth()+1) + '-' + pushDate.getFullYear());
d.setDate(d.getDate() + 7);
}
I am using this function to get all mondays in a month, current month.
How can I adapt this code to get all remaining mondays in the year?
Just loop through the year instead of the month. The code is the same as yours, it works fine. just changed month -> year and getMonth() -> getYear()
var d = new Date(),
year = d.getYear(),
mondays = [];
d.setDate(1);
// Get the first Monday in the month
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getYear() === year) {
var pushDate = new Date(d.getTime());
mondays.push(pushDate.getDate() + '-' + (pushDate.getMonth()+1) + '-' + pushDate.getFullYear());
d.setDate(d.getDate() + 7);
}
var x = new Date();
//set the financial year starting date
x.setFullYear(2016, 03, 01);
//set the next financial year starting date
var y = new Date();
y.setFullYear(2017, 03, 01);
var j = 1;
var count = 0;
//getting the all mondays in a financial year
for (var i = 0; x < y; i += j) {
if (x.getDay() === 1) {
document.write("Date : " + x.getDate() + "/" +
(x.getMonth() + 1) + "<br>");
x = new Date(x.getTime() + (7 * 24 * 60 * 60 * 1000));
j = 7;
count++;
} else {
j = 1;
x = new Date(x.getTime() + (24 * 60 * 60 * 1000));
}
}
document.write("total mondays : " + count + "<br>");
This is just an alternative, it uses a simpler method of getting the first day of the month.
// Get all Mondays in year from provided date
// Default today's date
function getMondays(d) {
// Copy d if provided
d = d ? new Date(+d) : new Date();
// Set to start of month
d.setDate(1);
// Store end year and month
var endYear = d.getFullYear() + 1;
var endMonth = d.getMonth();
// Set to first Monday
d.setDate(d.getDate() + (8 - (d.getDay() || 7)) % 7);
var mondays = [new Date(+d)];
// Create Dates for all Mondays up to end year and month
while (d.getFullYear() < endYear || d.getMonth() != endMonth) {
mondays.push(new Date(d.setDate(d.getDate() + 7)));
}
return mondays;
}
// Get all Mondays and display result
// SO console doensn't show all results
var mondays = getMondays();
mondays.forEach(function(mon) {
console.log(mon.toLocaleString(void 0, {
weekday: 'short',
day: 'numeric',
month: 'short',
year: 'numeric'
}));
});
// Count of Mondays, not all shown in SO console
console.log('There are ' + mondays.length + ' Mondays, the first is ' + mondays[0].toString())
With date-fns
https://date-fns.org/v2.28.0/docs/eachWeekOfInterval
eachWeekOfInterval({
start: new Date('2022/01/01'),
end: new Date('2022/5/31')
}, { weekStartsOn: 1 })
I got this from another stack question
incr_date(date_str){
let parts = date_str.split("-");
let dt = new Date(
parseInt(parts[0], 10), // year
parseInt(parts[1], 10) - 1, // month (starts with 0)
parseInt(parts[2], 10) // date
);
dt.setDate(dt.getDate() + 1);
parts[0] = "" + dt.getFullYear();
parts[1] = "" + (dt.getMonth() + 1);
if (parts[1].length < 2) {
parts[1] = "0" + parts[1];
}
parts[2] = "" + dt.getDate();
if (parts[2].length < 2) {
parts[2] = "0" + parts[2];
}
return parts.join("-");
}
It works but how can I convert this function to decrement the date instead of increment?
I'm doing this on a react native component so I dont want to import any javascript libraries like moment.js
function dateAdd(dte){
var date = new Date(dte);
date.setDate(date.getDate() + 1);
console.log("add one day= "+date)
}
function datesub(dte){
var date = new Date(dte);
date.setDate(date.getDate() - 1);
console.log("minus one day = "+ date)
}
dateAdd("01-01-2017")
datesub("01-01-2017")
I'd convert the string to Javascript understandable format, increment a day and convert it back to user understandable format. I'm using the flag(Boolean) to determine weather to Increment the date and vice versa.
var convertDate = function(dt, flag) {
var dateArr = dt.split('-');
var tempDate = new Date();
var mm = dateArr[1] - 1; //Javascript considers 0 as Jan
tempDate.setFullYear(dateArr[0]);
tempDate.setMonth(mm);
tempDate.setDate(dateArr[2]);
if (flag) {
tempDate.setDate(tempDate.getDate(dateArr[2]) + 1);//Add's one day
} else {
tempDate.setDate(tempDate.getDate(dateArr[2]) - 1);//Sub's one day
}
var userFriendlyMonth = (Number(tempDate.getMonth()) + 1); //user considers 1 as Jan
return tempDate.getFullYear() + '-' + userFriendlyMonth + '-' + tempDate.getDate();
}
document.getElementById("increment").innerHTML = convertDate('2018-11-30', true);
document.getElementById("decrement").innerHTML = convertDate('2018-11-30', false);
<div>Increment: <span id="increment"></span></div>
<div>Decrement: <span id="decrement"></span></div>
I want to get all dates in between 2 dates. So here I have mentioned statdate is date and end date is weekdate. In between 2 dates I want all dates.
Actully I am getting all dates But Not proper Format ,what i want in this format DD/MM/YY.
Now I am Getting in default Format (Sat Jun 09 2007 17:46:21)
$(document).ready(function () {
$("#day").click(function () {
startJsonSession();
return false;
});
function startJsonSession() {
var inputdate = $('#inputdate').val();
//alert("Input Date!!!" + inputdate );
var d = new Date(inputdate);
var nowMS = d.getTime(); // get # milliseconds for today
//alert(nowMS);
var week = 1000 * 60 * 60 * 24 * 7; // milliseconds in one week
//alert(week);
var oneWeekFromNow = new Date(nowMS + week);
//alert("oneWeekFromNow!!!" + oneWeekFromNow);
var fromdate = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if (fromdate < 10) {
fromdate = "0" + fromdate;
}
if (month < 10) {
month = "0" + month;
}
//var date = fromdate + "/" + month + "/" + year;
var date = year + "/" + month + "/" + fromdate;
alert("InputDate!!!!" + date);
//var weekdate=oneWeekFromNow.getDate() + "/" + month + "/" + year;
var weekdate = year + "/" + month + "/" + oneWeekFromNow.getDate();
alert("weekdate!!!" + weekdate);
var tomorrow = new Date(d.getTime() + (24 * 60 * 60 * 1000));
var tomorrowdate = tomorrow.getDate();
var month1 = tomorrow.getMonth() + 1;
var year1 = tomorrow.getFullYear();
if (tomorrowdate < 10) {
tomorrowdate = "0" + tomorrowdate;
}
if (month1 < 10) {
month1 = "0" + month1;
}
//var nextday = tomorrowdate + "/" + month1 + "/" + year1;
var nextday = year1 + "/" + month1 + "/" + tomorrowdate;
alert("tomorrow!!!!" + nextday);
var d1 = new Date(date);
alert("D1!!!!!" + d1.);
var d2 = new Date(weekdate);
var aDates = [];
do {
aDates.push(d1.toString());
d1.setDate(d1.getDate() + 1);
}
while (d1 <= d2);
alert("Dates!!!" + aDates);
//alert(aDates.join("\n"));
}
});
You can do it in this way
$("#getDate").click(function () {
var start = $("#startdate").datepicker("getDate"),
end = $("#enddate").datepicker("getDate");
currentDate = new Date(start),
between = [];
while (currentDate < end) {
between.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
for (var i = 0; i < between.length; i++) {
var date = $.datepicker.formatDate('dd/mm/yy', new Date(between[i]));
between[i] = date;
}
console.log(between)
})
Here 'between' is the array which contains all your required Date
SEE DEMO HERE
alert("Dates!!!" + aDates.getDate()+"/"+ (aDates.getMonth()+1)+"/"+ aDates.getFullYear());
You seem to want to get a array of date strings in d/m/y format given an input string in the same format. The following functions will do that.
// Parse a string in dmy format
// return a date object, NaN or undefined
function parseDMY(s) {
var b = s.match(/\d+/g);
if (b) {
return new Date(b[2], --b[1], b[0]);
}
}
// Given a date object, return a string in dd/mm/yyyy format
function formatDMY(date) {
function z(n){return (n<10? '0' : '') + n;}
return z(date.getDate()) + '/' + z(date.getMonth() + 1) + '/' + date.getFullYear();
}
function getWeekDates(s) {
var d = parseDMY(s);
var dates = [];
if (d) {
for (var i=0; i<7; i++) {
dates.push(formatDMY(d));
d.setDate(d.getDate() + 1);
}
return dates;
}
}
console.log(getWeekDates('7/7/2014').join());
// 07/07/2014,08/07/2014,09/07/2014,10/07/2014,11/07/2014,12/07/2014,13/07/2014
Note that adding 1 day to a date is preferred over adding milliseconds as it allows the Date object to take account of daylight saving changes that might be involved.
I am trying to display the text 'Oct 09, 2012'. Instead it is not running the function and is displaying a lot of unnessecary date text. Does anyone know what I am doing wrong?
You can play with my jsfiddle... http://jsfiddle.net/UP3fd/
Here is the code...
var myDate = new Date();
convertDate(myDate);
myDate.setFullYear(2012, 9, 9);
document.write(myDate);
function convertDate(d) {
var day = d.getDate();
if (day < 10) {
day = "0" + day;
}
var year = d.getFullYear();
var month = d.getMonth();
var months=["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct"," Nov","Dec"];
var currentMonth = months[month];
return (currentMonth + " " + day + ", " + year);
}
You are calling your function before you set your date, and you are not saving/outputting the return value anywhere.
var myDate = new Date();
myDate.setFullYear(2012, 9, 9);
document.write( convertDate(myDate) );
function convertDate(d) {
var day = d.getDate();
if (day < 10) {
day = "0" + day;
}
var year = d.getFullYear();
var month = d.getMonth();
var months=["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct"," Nov","Dec"];
var currentMonth = months[month];
return (currentMonth + " " + day + ", " + year);
}
var strDate = addZero(d.getDate()) + "/" + addZero((d.getMonth() + 1))+
"/" +d.getFullYear();
alert("strDate :"+strDate)
return strDate;
}
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
This is the correct code:
var myDate = new Date();
myDate.setFullYear(2012, 9, 9);
myDate = convertDate(myDate);
document.write(myDate);
[...]
Here's the corrected code, this should return you what you are expecting.
var myDate = new Date();
myDate.setFullYear(2012, 9, 9);
var newDate = convertDate(myDate);
document.write(newDate);
function convertDate(d) {
var day = d.getDate();
if (day < 10) {
day = "0" + day;
}
var year = d.getFullYear();
var month = d.getMonth();
var months=["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct"," Nov","Dec"];
var currentMonth = months[month];
return (currentMonth + " " + day + ", " + year);
}