Extract hour and minute from date function - javascript

I want to pass the time variable extracted from the database as a Date function in jQuery and want to extract hours and minutes from it and want to store it in a javascript variable.
var time="<?php echo $row['time']; ?>";
var time=new Date(time);
var hrs=time.getHours();
var min=time.getMinutes();
Please find if there is any error in this code.

Without more knowledge I can't really give you an answer.
But its likely that you're expecting a Date Object, when in reality your DB is returning something else.
(Maybe a string?, a number?)
Make sure what type of data is exactly storen in your "time" variable. Would be my suggestion because I dont see errors in the code. Must be the logic
Really hope this helped but more insight into what your DB is doing would help getting a clear answer :)
Good Luck !

You could find answers for this all over Stackoverflow or read the docs on the date object.
However, here is an answer you might like
var myMinutes = 1; // This represent 1 minute subtraction
var myHours = 60; // This represent 60 minutes subtraction which is 1 hour
var dateMSubObject= new Date(oldDateObject.getTime() - myMinutes*60000); //Substracting your minutes variable
var dateHSubObject= new Date(oldDateObject.getTime() - myHours*60000); //Substracting your hours variable
To make it more managable you could do hours like this aswell for etc 24 hours
var myHours = 60*24; // This represent 24 hours subtraction
You could also make the above code a function which wil take paramters like units, type and from that return your desired result
The 60000 part is milliseconds and represents 1 minute.
And welcome to StackOverflow, if you take some time exploring the website you will quickly be able to find the most common questions usually followed by great answers :)

This did it for me:
let jsdate = new Date(unixtimestamp+1000);
example in use:
let a = new Date();
console.log("a ="+a)
let stamp = a.getTime()
console.log("stamp ="+stamp) // timestamp
let newTimeObj = new Date(stamp*1000)
console.log("newTimeObj :::::::"+newTimeObj)
OUTPUT::::

You need to convert the UNIX Timestamp(in seconds) which is coming from your PHP code to milliseconds, and then pass it as a parameter to a Date object.
Consider the below example in JavaScript:
//UNIX Timestamp from your PHP code
let timeInUNIXTimeStamp = "1581653281";
// Create a new JavaScript Date object based on the timestamp
// Multiplied by 1000 to convert it into milliseconds, from seconds, as Date object works in milliseconds
var date = new Date(timeInUNIXTimeStamp * 1000);
// Get Hours part from the timestamp
var hours = date.getHours();
// Get Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Will display time in H:M format
var timeInHMSFormat = hours + ':' + minutes.substr(-2);
console.log(timeInHMSFormat);
You can same achieve in PHP also, there you need to convert UNIX Timestamp to H:M format, using the date() function, where the first parameter will the format you wanted and the second will be your UNIX Timestamp.
Example: date("h:i", 1581653281);
Where h is hours, in 12-hours format
i is minutes
Read move about PHP's data() function Date function in php
Consider PHP the code below, inside your JavaScript:
var time="<?php echo date('h:i', $row['time']); ?>";
//Now Split the above string into array
var timeArray = time.split(":");
var hours = timeArray[0];
var minutes = timeArray[1];
For more detail see this answer Convert UNIX Timestamp

Related

Need help subtracting time and date with Google SCRIPT

I have this code here:
var date = a.created_at_timestamp.substring(0,10)
var time = a.created_at_timestamp.substring(11,19)
And both these values return strings with these values:
date = 2020-05-19 //
Time = 17:00:08
I need to subtract 3 hours since it's coming in GMT time and I'm on GMT-3. Therefore, I thought about adding them together, subtracting three hours, and putting them apart again. Something like:
Orig Date: 20/05/19 //
Orig Time: 20:15:19
Time + Date: 20/05/19 20:15 //
Time + Date - 3h: 20/05/19 17:15
New Date: 20/05/19 00:00 //
New Time: 17:15:19
I tried converting it to milliseconds as suggested in other post here, doing with formulas, where a function would trigger formulas adding both cells, which I was able to do, but couldn't tear them apart together. In addition, if possible, I'd like to do it inside the script.
Can someone help me with that?
I'm new at this and I'm somewhat used to VBA. Tried some things from VBA, but they don't really apply here.
Instead of having separate strings for date and time, it'd likely be easier to just create a new Date object with both combined.
var dateTime = new Date(a.created_at_timestamp.substring(0,19));
You can then subtract 3 hours by doing:
var timeOffset = 3 * 60 * 60 * 1000; // 3hrs of millis
var offsetDate = new Date(dateTime.getTime() - timeOffset);

Timesheet hours difference in moment.js

I have a string '08:30-16:30' describing working hours.
I also have the time someone has worked, in HH:mm format,eg.09:15
What is the easiest-fastest way to convert them in dates and find the difference in HH:mm format ?
Should i use Moment.js?
Also,i need the difference in minutes or seconds so that i can do comparisons with that.
I would be grateful if you could give me some examples.
For finding the difference between the working hours, you could make use of MomentJS.
Example:
var working_hours = '08:30-16:30';
var hours_arr = working_hours.split('-'); // Gives an array with ['08:30', '16:30']
var start = moment(hours_arr[0], "HH:mm");
var end = moment(hours_arr[1], "HH:mm");
var duration = moment.duration(end.diff(start));
var minutes = parseInt(duration.asMinutes());
The minutes variable would contain the difference in minutes.

get time different (minutes) in javascript

How do I calculate the difference in minutes given two strings. For example say I have
11:00
11:30
But of course the second string could be 12:11 so I can't subtract just the minutes.
first use javascript to convert the strings to time, then subtract, then convert back to strings
like this:
x = new Date("1/1/01 11:00")
y = new Date("1/1/01 11:30")
// now y-x has difference in milliseconds
// (y-x)/1000 is difference in seconds, etc
The data 1/1/01 is just being used as a dummy value, but the one thing you might have to worry about is are the times on different days, if so you will have to use 1/2/01 for the second time. Unless of course you always know the times are in the same day, but if they can cross "midnight" then you have to adjust for that.
You may want to use http://momentjs.com/ which will take care of the details for you.
When looking for getting metrics such as date , hour , minutes, seconds from the date difference, it's a lot easier to use basic notations as listed here
var x = new Date(new Date().getTime() + 11.5*60*60000); // adds 11 hours - 30 minutes
var y = new Date(new Date().getTime() + 11*60*60000); // adds 11 hours
alert(x.getMinutes() - y.getMinutes()); // gives the difference = 30
Here's an example : https://jsfiddle.net/DinoMyte/157knmgn/

How to read the correct time/duration values from Google Spreadsheet

I'm trying to get from a time formatted Cell (hh:mm:ss) the hour value, the values can be bigger 24:00:00 for example 20000:00:00 should give 20000:
Table:
if your read the Value of E1:
var total = sheet.getRange("E1").getValue();
Logger.log(total);
The result is:
Sat Apr 12 07:09:21 GMT+00:09 1902
Now I've tried to convert it to a Date object and get the Unix time stamp of it:
var date = new Date(total);
var milsec = date.getTime();
Logger.log(Utilities.formatString("%11.6f",milsec));
var hours = milsec / 1000 / 60 / 60;
Logger.log(hours)
1374127872020.000000
381702.1866722222
The question is how to get the correct value of 20000 ?
Expanding on what Serge did, I wrote some functions that should be a bit easier to read and take into account timezone differences between the spreadsheet and the script.
function getValueAsSeconds(range) {
var value = range.getValue();
// Get the date value in the spreadsheet's timezone.
var spreadsheetTimezone = range.getSheet().getParent().getSpreadsheetTimeZone();
var dateString = Utilities.formatDate(value, spreadsheetTimezone,
'EEE, d MMM yyyy HH:mm:ss');
var date = new Date(dateString);
// Initialize the date of the epoch.
var epoch = new Date('Dec 30, 1899 00:00:00');
// Calculate the number of milliseconds between the epoch and the value.
var diff = date.getTime() - epoch.getTime();
// Convert the milliseconds to seconds and return.
return Math.round(diff / 1000);
}
function getValueAsMinutes(range) {
return getValueAsSeconds(range) / 60;
}
function getValueAsHours(range) {
return getValueAsMinutes(range) / 60;
}
You can use these functions like so:
var range = SpreadsheetApp.getActiveSheet().getRange('A1');
Logger.log(getValueAsHours(range));
Needless to say, this is a lot of work to get the number of hours from a range. Please star Issue 402 which is a feature request to have the ability to get the literal string value from a cell.
There are two new functions getDisplayValue() and getDisplayValues() that returns the datetime or anything exactly the way it looks to you on a Spreadsheet. Check out the documentation here
The value you see (Sat Apr 12 07:09:21 GMT+00:09 1902) is the equivalent date in Javascript standard time that is 20000 hours later than ref date.
you should simply remove the spreadsheet reference value from your result to get what you want.
This code does the trick :
function getHours(){
var sh = SpreadsheetApp.getActiveSpreadsheet();
var cellValue = sh.getRange('E1').getValue();
var eqDate = new Date(cellValue);// this is the date object corresponding to your cell value in JS standard
Logger.log('Cell Date in JS format '+eqDate)
Logger.log('ref date in JS '+new Date(0,0,0,0,0,0));
var testOnZero = eqDate.getTime();Logger.log('Use this with a cell value = 0 to check the value to use in the next line of code '+testOnZero);
var hours = (eqDate.getTime()+ 2.2091616E12 )/3600000 ; // getTime retrieves the value in milliseconds, 2.2091616E12 is the difference between javascript ref and spreadsheet ref.
Logger.log('Value in hours with offset correction : '+hours); // show result in hours (obtained by dividing by 3600000)
}
note : this code gets only hours , if your going to have minutes and/or seconds then it should be developped to handle that too... let us know if you need it.
EDIT : a word of explanation...
Spreadsheets use a reference date of 12/30/1899 while Javascript is using 01/01/1970, that means there is a difference of 25568 days between both references. All this assuming we use the same time zone in both systems. When we convert a date value in a spreadsheet to a javascript date object the GAS engine automatically adds the difference to keep consistency between dates.
In this case we don't want to know the real date of something but rather an absolute hours value, ie a "duration", so we need to remove the 25568 day offset. This is done using the getTime() method that returns milliseconds counted from the JS reference date, the only thing we have to know is the value in milliseconds of the spreadsheet reference date and substract this value from the actual date object. Then a bit of maths to get hours instead of milliseconds and we're done.
I know this seems a bit complicated and I'm not sure my attempt to explain will really clarify the question but it's always worth trying isn't it ?
Anyway the result is what we needed as long as (as stated in the comments) one adjust the offset value according to the time zone settings of the spreadsheet. It would of course be possible to let the script handle that automatically but it would have make the script more complex, not sure it's really necessary.
For simple spreadsheets you may be able to change your spreadsheet timezone to GMT without daylight saving and use this short conversion function:
function durationToSeconds(value) {
var timezoneName = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
if (timezoneName != "Etc/GMT") {
throw new Error("Timezone must be GMT to handle time durations, found " + timezoneName);
}
return (Number(value) + 2209161600000) / 1000;
}
Eric Koleda's answer is in many ways more general. I wrote this while trying to understand how it handles the corner cases with the spreadsheet timezone, browser timezone and the timezone changes in 1900 in Alaska and Stockholm.
Make a cell somewhere with a duration value of "00:00:00". This cell will be used as a reference. Could be a hidden cell, or a cell in a different sheet with config values. E.g. as below:
then write a function with two parameters - 1) value you want to process, and 2) reference value of "00:00:00". E.g.:
function gethours(val, ref) {
let dv = new Date(val)
let dr = new Date(ref)
return (dv.getTime() - dr.getTime())/(1000*60*60)
}
Since whatever Sheets are doing with the Duration type is exactly the same for both, we can now convert them to Dates and subtract, which gives correct value. In the code example above I used .getTime() which gives number of milliseconds since Jan 1, 1970, ... .
If we tried to compute what is exactly happening to the value, and make corrections, code gets too complicated.
One caveat: if the number of hours is very large say 200,000:00:00 there is substantial fractional value showing up since days/years are not exactly 24hrs/365days (? speculating here). Specifically, 200000:00:00 gives 200,000.16 as a result.

How do I convert current time to GMT?

I need to get the value of 00:00:00 AM GMT(12am) for the current day and then convert it to unix time. How would/should I go about doing that in javascript? Is there an outside data source that is more reliable then server time? I will be doing this in node on the server.
Thanks!
EDIT: This is what I did. Do you see any problems with this? Thanks again!
date = new Date()
start_date = Date.UTC(date.getFullYear(),date.getUTCMonth(),date.getUTCDate()) / 1000
Your method is right, but you have got a nasty bug in there, you are mixing local year with UTC date and month, for a few hours around new year, depending on time zone, the local and the UTC year is different, so if you use the wrong year your result will be a whole year off.
There are two interpretations of your question. Either you want a result based on the local time, so the result at any given time will depend on the time zone. Or you want a result based on UTC time that is the same no matter time zone, but sometimes for some users the result will not be the local date.
Local time:
date = new Date()
start_date = Date.UTC(date.getFullYear(),date.getMonth(),date.getDate()) / 1000
UTC:
date = new Date()
start_date = Date.UTC(date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate()) / 1000
This is a good place to start:
var now = new Date();
var then = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var epoch = then.getTime();
Not sure what you want to do about DST, so you'll need to look at:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset
Edit: To allow for different timezones:
var off = now.getTimezoneOffset() * 60000; /* tz is in mins so multiply to ms */
var midnight = new Date(then.getTime() - off);
var epoch = midnight.getTime();
These links have some good answers. I love epochconverter.com it's saved me many hours of frustration. The essence of the answer is to use the Javascript Date object to handle all the nastiness of converting dates around. This is generally what you should do in any languages. If you are doing date manipulation by hand you will get it wrong.
http://www.epochconverter.com/programming/#javascript
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
This is what I ended up doing for anyone else looking at this question.
date = new Date()
start_date = Date.UTC(date.getFullYear(),date.getUTCMonth(),date.getUTCDate()) / 1000
Please let me know if you see any reason this wouldn't work.

Categories

Resources