javascript date object doesnt return result - javascript

i have this calendar table(its bunch of floated divs.. not <table>),
my user should be able to click anywhere on row to add new booking. problem is how to calculate the time where he clicked.
so i use:
$('day-column').click(function(e){
var posY = $(this).offset().top;//get offset of click
var pos=(e.pageY - posY)* 60 * 1000;//convert it into millisec (since 1px=1min)
var start=8 * 60 * 60 * 1000;//covert starting hour 8:00 into millisec
var d = new Date();//create date object
d.setMilliseconds((start+pos));//set obj millisec
console.log(d.getHours()+':'+d.getMinutes());//try to extract new hour and time
});
Why is this not working ?? am i doing something wrong ?

I suggest using :
http://momentjs.com/
will support on all browsers , simple , and you can have the format option.
which i think you will like.

Related

Date Math for Google Apps Script for User Submitted Dates

I created a Google Form to collect user input, including the expiration date of a contract.
I need to create a reminder date (6 months before the expiration date) in a new column of the gsheets that is linked to the form. Using the Event Object namedValues, I extracted the expiration date from gsheet. I converted the date to milliseconds and subtracted the number of milliseconds equal to 6 months (or thereabouts). However, the output that got sent back to the googlesheet is an undefined number.
I must be misunderstanding something and was hoping someone more skilled in this can help me out. Is the data type wrong? Thanks for any illumination you can provide.
function onFormSubmit(e) {
var responses = e.namedValues;
var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
var expireDate = responses['Expiration Date'][0].trim();
var expireDate_ms = expireDate * 1000; // converting to milliseconds
var noticeDate = expireDate_ms - (183 * MILLIS_PER_DAY);
// Create a new column to store the date to send out notice of expiration or renewal
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRow();
var column = e.values.length + 1;
sheet.getRange(row, column).setValue(noticeDate);
}
I’d recommend you to use a formula instead:
={"Reminder"; ARRAYFORMULA(IF(NOT(ISBLANK(B2:B)); EDATE(B2:B; -6); ""))}
Add this to the header of an empty column, it will generate all data in that column for you. Change B for the column you have the expiration date on.
If you really need to use Google Apps Script you can, but JavaScript is notorious for having bad date support (at least without an external library). To do it, you’ll have to manually parse the string, modify the date and format it back to the date number:
const dateParts = e.namedValues['Expiration Date'][0].trim().split('/')
const date = new Date(
Number(dateParts[2]), // Year
Number(dateParts[1]) - 1 - 6, // Month. -1 because January is 0 and -6 for the 6 months before
Number(dateParts[0]) // Day
)
const numericDate = Math.floor((date.getTime() - new Date(1900, 0, 1).getTime()) / (1000 * 60 * 60 * 24))
This example only works if the format used in the sheet is DD/MM/YYYY.
The numeral value of date is the number of days since the first day of 1900 (link to documentation). So we need to subtract it and change it from milliseconds to days. Math.floor ensures that it’s not decimal.
You can set numericDate to the cell but make sure the numeric format is Date.
References
EDATE - Docs Editors Help
ARRAYFORMULA - Docs Editors Help
Date - JavaScript (MDN)
DATE - Docs Editor Help
Marti's answer was helpful but the math didn't quite work out because the suggested solution was to minus 6 from the month retrieved. But the reminder date is supposed to be 6 months from the date (taking into account the year and the date), so it doesn't quite work.
The solution I worked out is the following:
function onFormSubmit(e) {
const expireDateParts = e.namedValues['Expiration Date'][0].trim();
if (expireDateParts != ""){
expireDateParts.split('/');
var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
const expireDate = new Date(
Number(expireDateParts[2]), // Year
Number(expireDateParts[0]) - 1, // Month. -1 because January is '0'
Number(expireDateParts[1]) // Day
);
const reminderNumericDate = Math.floor((expireDate.getTime() - 183 * MILLIS_PER_DAY));
var reminderDate = formatDate(reminderNumericDate);
// Create a new column to store the date to send out notice of expiration or renewal
var sheet = SpreadsheetApp.getActiveSheet();
var row = sheet.getActiveRange().getRow();
var column = 14 // hard-coded to Column 0;
sheet.getRange(row, column).setValue(reminderDate);
// Set up Schedule Send Mail
createScheduleSendTrigger(reminderNumericDate);
var status = 'Scheduled';
sheet.getRange(row, column+1).setValue(status);
}
}

How to convert a string to time in javascript

I'm trying to create a countdowntimer in Javascript. There are a lof of examples on the internet. I'm trying to adjust these to my own needs. I want a countdown timer that, when started, countsdown to the whole hour. For example, if I run the code at 13:15 it wil count down to 14:00.
The problem I have is getting the time to countdown to.
var cd = new Date("Jan 5, 2021 15:37:25").getTime();
In the above example you have a defined date. I'm trying to change this to a time to the first upcoming hour. Below is what I have:
var countdowndate = newDate("cd.getMonth, cd.getYear (cd.getHour + 1):00:00").getTime();
This isn't working. What am I doing wrong here? Any help is appreciated.
Here's a very expressive way of solving this:
Get the current time stamp, floored to the last full minute.
Get how many full minutes remain until the next hour, transform to milliseconds.
Sum up the results of 1 and 2.
function getBeginningOfNextHour() {
const msPerMinute = 60 * 1000;
const currentDate = new Date();
const currentDateTimestampRoundedToMinute = Math.floor(+currentDate / msPerMinute) * msPerMinute;
const msUntilNextHour = (60 - currentDate.getMinutes()) * msPerMinute;
return new Date(currentDateTimestampRoundedToMinute + msUntilNextHour);
}
console.log(getBeginningOfNextHour());

How to make two timepickers behave like google calendar?

I try to make my timepickers behave like the ones in google calendar. What I try to achieve is that if I set the start time from 10:00 to 11:00, the 2nd should follow from 11:00 to 12:00. If I set the 2nd picker from 11 to 13, the difference is now 2 hours and if I adjust the first one, the 2nd should move +2 or -2 hours depending if its earlier or later on the day.
My current jquery code is now
var d = new Date();
var start_time = $('#calendarentryform-start_time').val();
var end_time = $('#calendarentryform-end_time').val();
var diff = ( new Date('1970-01-01 ' + end_time) - new Date('1970-01-
01 ' + start_time) ) / 1000 / 60 / 60;
var new_end_time = start_time + diff;
$('#calendarentryform-start_time').on('change',function() {
$('#calendarentryform-end_time').val(new_end_time);
}
);
It manage to find for example the hour difference on 1 hour, like the calculation is correct. But when I try to add that hour for new_end_time it just post 12:001 instead of 13:00 or whatever the time is supposed to be set to. I also want it to be able to find 1,5 hours, 2,5 hours etc.
I just dont seem to get it right.

Setting timezone for running clock in JavaScript

Good days guys. I have this nice and clean code for a running clock.
<script type="text/javascript">
function DisplayTime(){
if (!document.all && !document.getElementById)
return
timeElement=document.getElementById? document.getElementById("curTime"): document.all.tick2
var CurrentDate=new Date()
var hours=CurrentDate.getHours()
var minutes=CurrentDate.getMinutes()
var seconds=CurrentDate.getSeconds()
var DayNight="PM"
if (hours<12) DayNight="AM";
if (hours>12) hours=hours-12;
if (hours==0) hours=12;
if (minutes<=9) minutes="0"+minutes;
if (seconds<=9) seconds="0"+seconds;
var currentTime=hours+":"+minutes+":"+seconds+" "+DayNight;
timeElement.innerHTML="<font style='font-family:Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&subset=latin,cyrillic-ext,latin-extfont-size:14px;color:#fff;'>"+currentTime+"</b>"
setTimeout("DisplayTime()",1000)
}
window.onload=DisplayTime
</script>
My only problem is it's based the system time. How can I set the timezone so that it will display the correct time based on the timezone specified?
There's nothing built into the JavaScript Date object that handles any timezones other than local (system) time and UTC.
You can do it by giving your Date instance the wrong time, using the delta between one of those timezones (local or UTC) and the time zone you want to use. It's easier if you use UTC.
So for instance, say we want our time in GMT+01:00:
var dt = new Date();
dt.setTime(dt.getTime() + (60 * 60 * 1000));
// ^^^^^^^^^^^^^^---- one hour in milliseconds,
// which is our offset from UTC/GMT
var hours = dt.getUTCHours(); // Use UTC methods to get time
var minutes = dt.getUTCMinutes();
var seconds = dt.getUTCSeconds();
Time stuff, particularly with timezones, is hard. You might look at using a library for it, although for just this sort of clock that would be overkill. One good library is MomentJS (which has a timezone add-on).
You can use getTimezoneOffset method of the Date object. It gives you the timezone offset, according to your timezone in minutes.
So in order to get the current time in UTC (+0 timezone) you can do something of the sort:
var tzOffset = CurrentDate.getTimezoneOffset();
// some timezones are not set hours, so we must calculate the minutes
var minutesOffset = parseInt(tzOffset%60,10);
// the offset hours for the timezone
var hoursOffset = parseInt(tzOffset/60, 10);
Then you need to do some math in your code to account for the offset:
var hours = CurrentDate.getHours() + hoursOffset;
var minutes = CurrentDate.getMinutes() + minutesOffset;
This would account for your timezone. If you want to calculate another timezone, that you specify, change the tzOffset above to show your timezone.
var tzOffset = CurrentDate.getTimezoneOffset() + TIMEZONE_HOURS*60;
TIMEZONE_HOURS is the timezone in hours you want, e.g. if you want UTC+3, you must set TIMEZONE_HOURS to 3.
As a whole timezones are a bit complicated task because they change a lot and there are some caveats with them. If you want to dwell more into this, check this answer in another question on SO
I have implemented your working code by adding one more function to obtain what you want. See this will help
function DisplayTime(timeZoneOffsetminutes){
if (!document.all && !document.getElementById)
return
timeElement=document.getElementById? document.getElementById("curTime"): document.all.tick2
var requiredDate=getTimeZoneTimeObj(timeZoneOffsetminutes)
var hours=requiredDate.h;
var minutes=requiredDate.m;
var seconds=requiredDate.s;
var DayNight="PM";
if (hours<12) DayNight="AM";
if (hours>12) hours=hours-12;
if (hours==0) hours=12;
if (minutes<=9) minutes="0"+minutes;
if (seconds<=9) seconds="0"+seconds;
var currentTime=hours+":"+minutes+":"+seconds+" "+DayNight;
timeElement.innerHTML="<font style='font-family:Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&subset=latin,cyrillic-ext,latin-extfont-size:14px;color:#fff;'>"+currentTime+"</b>"
setTimeout("DisplayTime(-330)",1000)
}
window.onload=DisplayTime(-330);
function getTimeZoneTimeObj(timeZoneOffsetminutes){
var localdate = new Date()
var timeZoneDate = new Date(localdate.getTime() + ((localdate.getTimezoneOffset()- timeZoneOffsetminutes)*60*1000));
return {'h':timeZoneDate.getHours(),'m':timeZoneDate.getMinutes(),'s':timeZoneDate.getSeconds()};
}
#curTime{
background-color:#000;
}
<div id="curTime"></div>
visit this link as a reference
example:
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
You can try using moment.js
It is very nice library which handles timezones too.

Need to create a html page for adding X days to D.O.B

I'm looking for a HTML code that adds a fixed number of days to an entered Date of Birth. Thanks a lot! Even a partial code is much appreciated!
Here is how I'd do it. The function daysFromDate returns a Date object you can use. Instead of passing the DOB as a string you can also update it to use a Date object.
/*
days is the number of days to add, and dob a string like "4/24/2011"
*/
function daysFromDate(days, dob) {
var dates = dob.split('/');
var daysToMilli = days * 60 * 60 * 24 * 1000;
var d = new Date(parseInt(dates[2]), parseInt(dates[0])-1, parseInt(dates[1]));
var newTime = d.getTime() + daysToMilli;
return new Date(newTime);
}
To get the date 20 days from now you call: daysFromDate(20, "4/24/2011");
VBScript has DateAdd() so it's pretty simple. If you prefer JavaScript, just Google "javascript dateAdd" -- there are a zillion solutions out there. Here's one:
http://www.solutionbot.com/2008/06/20/javascript-dateadd-function/

Categories

Resources