Node / Javascript Set Date Time - javascript

I have parameters startTime and endTime which are in the format of:
var time1 = "08:00";
var time2 = "23:00";
I need to compare whether the current date/time is in between these two periods:
var now = new Date();
if (now > time1 && now < time2)
{
console.log("We are in the time period");
}
It is impossible to change the input of time1 or time2.
I was thinking abotu converting time1 and time2 to a new Date format, however I am unsure how to go about this.
How would you go about it?
Thanks

You should do something like this:
var time1 = parseInt("08:00".substring(0,2));
var time2 = parseInt("23:00".substring(0,2));
var now = new Date();
if (now > new Date().setHours(time1) && now < new Date().setHours(time2))
{
console.log("We are in the time period");
}

Related

MomentJs subtract time to actual

I need to subtract actual time from a time variable (formatted in hh:mm:ss) and obtain the result in seconds, for example:
var time1 = "13:40:00";
var time1 = moment(time1, "HH:mm:ss");
var timeNow = ?
var time2 = time1 - timeNow // expressed in s
How can I achieve this?
I am not sure if I understood your needs fully but give this a try
var time1 = "13:40:00";
var time1 = moment(time1, "hh:mm:ss");
var time2 = time1.diff(moment(), 'seconds')
You can use moment diff to get the difference between two moment objects. In your case:
var time1 = '13:40:00';
var diff = moment().diff(moment(time1, 'HH:mm:ss'), 'seconds');
console.log(diff);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
Try this:
var time1 = moment.duration("24:40:00", "HH:mm:ss").asSeconds();
var timeNow =moment.duration(moment().format('HH:mm:ss'),"HH:mm:ss").asSeconds();
var log = time1-timeNow;

Jquery get age by input value

How do I calculate the age of a user, depending on the date entered in a textbox?
I want to be able to calculate the exact age of YYYY/MM/DD, so far I've only managed to do it by year.
The code I've tried so far:
function OnClick() {
var txtDate = $("#txtDate").val();
var date1 = new Date();
date1.setFullYear(txtDate);
var d1 = date1.getFullYear();
var date2 = new Date();
var d2 = date2.getFullYear();
var age = d2 - d1;
document.getElementById("Diven").innerHTML = age;
}
Any ideas?
When you set the date using this: new Date(birthYear, birthMonth, birthDay); you need to subtract 1 from the month. Months are counted from 00.
For example,
var testDate = new Date(1988,10,12) is Sat Nov 12 1988 00:00:00
You can try this alternate way:
var today = new Date();
var inputBirthDate= new Date(birthYear, birthMonth - 1, birthDay);
var age = today.getFullYear() - inputBirthDate.getFullYear();
var month = today.getMonth() - inputBirthDate.getMonth();
if (month < 0 || (month === 0 && today.getDate() < inputBirthDate.getDate())) {
age--;
}
console.log(age);
This will return you the correct age based on input birth date.
well since i can't make comment, im gonna do it here.
first thing i would do is use momentjs for every date releated thing in js
and if i understand your right, you want something like this?
How to get difference between 2 Dates in Years, Months and days using moment.js
You can use Math.floor and the modulo operator % for integer division:
function CalculateAge() {
var dob1 = $("#txtBirthday").val();
var age1 = document.getElementById("#age");
var dateAry = dob1.value.split("/");
var birthDay = parseInt(dateAry[0]);
var birthMonth = parseInt(dateAry[1]);
var birthYear = parseInt(dateAry[2]);
var birthDate = new Date(birthYear, birthMonth, birthDay);
var currentDate = new Date();
var age = currentDate - birthDate; // don't forget the var keyword
var days = Math.floor(age / 86400000); // no need to use a string
var years = Math.floor(days / 365); // quite inaccurate actually
var remaning_days = days % 365; // use modulo operator
age1.value = years; // no need to type-cast
}
function CalculateAge() {
var dob1 = $("#txtBirthday");
var age1 = $("#age");
var dateAry = dob1.val().split("/");
var birthDay = parseInt(dateAry[0]);
var birthMonth = parseInt(dateAry[1]);
var birthYear = parseInt(dateAry[2]);
var one_day=1000*60*60*24;
var date1 = new Date(birthYear, birthMonth, birthDay);
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2 = new Date();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
// Convert back to days and return
var t = difference_ms/one_day;
age1.val(t/365);
}
if you want approx year use Math.random in result

Get today date in Google Apps Script

How do I get the Today date on google appscript?
I need to write a code to input today´s date in a cell.
function changeDate(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
var date = //Today´s date!?!?!!?
var endDate = date;
sheet.getRange(5, 2).setValue(endDate);
}
Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
You can change the format by doing swapping the values.
dd = day(31)
MM = Month(12) - Case sensitive
yyyy = Year(2017)
function changeDate() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
// You could use now Date(); on its own but it will not look nice.
var date = Utilities.formatDate(new Date(), "GMT+1", "dd/MM/yyyy")
var endDate = date
}
The Date object is used to work with dates and times.
Date objects are created with new Date()
var now = new Date();
now - Current date and time object.
function changeDate() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
var date = new Date();
sheet.getRange(5, 2).setValue(date);
}
Google Apps Script is JavaScript, the date object is initiated with new Date() and all JavaScript methods apply, see doc here
The following can be used to get the date:
function date_date() {
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1; if(month.toString().length==1){var month =
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var hour = date.getHours(); if(hour.toString().length==1){var hour = '0'+hour;}
var minu = date.getMinutes(); if(minu.toString().length==1){var minu = '0'+minu;}
var seco = date.getSeconds(); if(seco.toString().length==1){var seco = '0'+seco;}
var date = year+'·'+month+'·'+day+'·'+hour+'·'+minu+'·'+seco;
Logger.log(date);
}
Easiest way, you can use javascript date object which is new Date().
function changeDate(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
var date = new Date();
sheet.getRange(5, 2).setValue(date);
}
But then you will get the whole time object. You just need to change the format in spreadsheet to time or date, whatever you like.
function myFunction() {
var sheetname = "DateEntry";//Sheet where you want to put the date
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetname);
// You could use now Date(); on its own but it will not look nice.
var date = Utilities.formatDate(new Date(), "GMT+5:30", "yyyy-MM-dd");
//var endDate = date;
sheet.getRange(sheet.getLastRow() + 1,1).setValue(date); //Gets the last row which had value, and goes to the next empty row to put new values.
}

calculate difference between two timestamp and get difference in unix timestamp

I want to calculate the difference between two dateTime, one date is submitted by user and other is current time:
user submitted time - now = difference in unix
user submitted time format is:
2014-03-26 10:52:00
Thanks for your help.
You can simply do this with getTime() which returns the number of milliseconds.
var ds = "2014-03-26 10:52:00";
var newDate = new Date(ds).getTime(); //convert string date to Date object
var currentDate = new Date().getTime();
var diff = currentDate-newDate;
console.log(diff);
Sometimes there are chance for cross browser compatibility in parsing the date string so it is better to parse it like
var ds = "2014-03-26 10:52:00";
var dateArray = ds.split(" "); // split the date and time
var ds1 = dateArray[0].split("-"); // split each parts in date
var ds2 = dateArray[1].split(":"); // split each parts in time
var newDate = new Date(ds1[0], (+ds1[1] - 1), ds1[2], ds2[0], ds2[1], ds2[2]).getTime(); //parse it
var currentDate = new Date().getTime();
var diff = currentDate - newDate;
console.log(diff); //timestamp difference
You can use MomentJS library
var user_submited_time = moment('2014-03-26 10:52:00');
var now = moment();
var value = user_submited_time - now;

checking if a current time falls in a particular interval in javascript

EDIT: Please take care to introduce UTC timing in your answer. Since doing things on client side will lead to different time zones.
In javascript, i can get the current time, hour and minute as follows:
var currentTime = new Date();
var currentHour = currentTime.getHours();
var currentMinute = currentTime.getMinutes();
Now i have to perform a task only if the current time false in an interval with a fixed time.
Say there is a fixed time 10:30 AM. Users can perform a certain task iff the current time, is 4 hours behind the current time or 1 hour ahead of the fixed time.
meaning users can perform the task from 6:30 AM to 11:30 AM.
I tried getting the current hours and doing
start = fixed_time - 4;
end = fixed_time + 1;
if currentHour< end or currentHour > start{
do some stuff;
}
But this ignores the minutes, how to take care of that?
Otherwise, how could i figure if the current time lies between 6:30 AM and 11:30 AM?
var currentTime = new Date();
var startTime = new Date(2012, 3, 8, 6, 30, 0, 0); //6:30am today
var endTime = new Date(2012, 3, 8, 11, 30, 0, 0); //11:30am today
if ((currentTime.getTime() > startTime.getTime()) && (currentTime.getTime() < endTime.getTime())
{
//current time is between start and end so do what you need to do
}
If you need it to be more dynamic you can
var currentTime = new Date();
var startTime = new Date();
startTime.setHours(6);
startTime.setMinutes(30);
var endTime = new Date();
endTime.setHours(11);
endTime.setMinutes(30);
if ((currentTime.getTime() > startTime.getTime()) && (currentTime.getTime() < endTime.getTime())
{
//current time is between start and end so do what you need to do
}
You can use getTime() method which returns the number of milliseconds since midnight Jan 1, 1970:
currentTime = (new Date()).getTime();
Then all you need is to calculate the difference between your fixed time and current time in milliseconds. 4 hours equals to 14,400,000 (4*60*60*1000) milliseconds.
You can compare dates to one another. So, using the current date and time you can compare that to dates with a fixed time set. Something like:
var now = new Date
,lower = new Date
,upper = new Date;
//determine limits
lower.setHours(6);
lower.setMinutes(30);
upper.setMinutes(30);
upper.setHours(11);
//tests
now = new Date('2012/04/08 22:00');
console.log(now >= lower && now <= upper); //=> false
now = new Date('2012/04/08 07:00');
console.log(now >= lower && now <= upper); //=> true
var startTime = '01 AM'; // or var startTime = '01:00 AM';
var endTime = '09 AM'; // or var startTime = '09:00 AM';
var now = new Date();
if(now < convert_time(endTime) && now > convert_time(startTime)){
alert("With in a range");
}else{
alert("Out of range");
}
function convert_actual_time(time) {
if(time.indexOf(" ") != -1){
split1 = time.split(" ");
splitTime = split1[0];
splitZone = split1[1];
}
if(splitTime.indexOf(":") != -1){
split2 = splitTime.split(":");
setHours = split2[0];
setMins = split2[1];
}else{
setHours = splitTime;
setMins = "00";
}
if(splitZone.toLowerCase() == "pm"){
setHours = parseInt(setHours)+12;
}
date = new Date();
date.setHours(setHours);
date.setMinutes(setMins);
return date;
}
Try with this code

Categories