I have a one time column in format 00:01:30 (HH:MM:SS). This column is a text format column.
this text column format convert to a time format column and create a new measure for the total time sum.
You can easily convert your Text column into Time using
Time = TIMEVALUE('Table'[Text])
But the problem is that the Time format doesn't support more than 24 hours, so your SUM will potentially lead to an overflow. Here's a workaround:
Create a calculated "Seconds" Column
Seconds =
VAR Time =
TIMEVALUE('Table'[Text])
RETURN
HOUR(Time) * 3600 + MINUTE(Time) * 60 + SECOND(Time)
Aggregate the Seconds with this Measure and convert back to a "Duration-like" format:
Total Duration =
VAR total_seconds =
SUM('Table'[Seconds])
VAR days =
QUOTIENT(total_seconds, 24 * 60 *60)
VAR rest1 =
MOD(total_seconds, 24 * 60 * 60)
VAR hours =
QUOTIENT(rest1, 60 * 60)
VAR rest2 =
MOD(total_seconds, 60 * 60)
VAR minutes =
QUOTIENT(rest2, 60)
VAR seconds =
MOD(rest2, 60)
RETURN
days & "." & FORMAT(hours, "0#") & ":" & FORMAT(minutes, "0#") & ":" & FORMAT(seconds, "0#")
Related
I have some text fields in an array. HH:MM:SS. I'm having two issues, one is when one of the fields is left blank, the app crashes and I want it to just read as "0" if blank. Second, I use below to convert HH:MM:SS to Minutes. I do 0:18:30 and the math below to decimal comes out to 18.5
Now how would I convert this back to HH:MM:SS? array[0] is hours, array[1] is minutes, array[2] is seconds.
stepOne = (Float(array[0])! * 60) + Float(array[1])! + (Float(array[2])! / 60)
What you need is to calculate the number of seconds instead of number of minutes. Using the reduce method just multiply the first element by 3600 and then divide the multiplier by 60 after each iteration. Next you can use DateComponentsFormatter to display the resulting seconds time interval using .positional units style to the user:
let array = [0,18,30]
var n = 3600
let seconds = array.reduce(0) {
defer { n /= 60 }
return $0 + $1 * n
}
let dcf = DateComponentsFormatter()
dcf.allowedUnits = [.hour, .minute, .second]
dcf.unitsStyle = .positional
dcf.zeroFormattingBehavior = .pad
let string = dcf.string(from: TimeInterval(seconds)) // "00:18:30"
If I have a date YYMMDDHHmmss such as 190525234530 how do I work out the smallest number of characters to represent this using 0-9a-z (36 characters)?
I believe there are 3,153,600,000 combinations (100 years * 365 days * 24 hours * 60 minutes * 60 seconds) which would fit into 32 bits. Does this mean I could represent these dates using 4 characters?
I am a bit lost as to how to do the conversion so if anyone could show me the maths that would be greatly appreciated.
I ended up doing this in JavaScript, I decided I wanted to compress to 6 characters so I created my own time which generates unique ID's for up to 68 years from 01/01/2019 which worked for me.
function getId() {
//var newTime = parseInt(moment().format("X")) - 1546300800;//seconds since 01/01/2019
var newTime = Math.floor((new Date()).getTime() / 1000) - 1546300800;//seconds since 01/01/2019
var char = "0123456789abcdefghijklmnopqrstuvwxyz";//base 36
return char[Math.floor(newTime / 36**5)]+
char[Math.floor(newTime%36**5 / 36**4)]+
char[Math.floor(newTime%36**4 / 36**3)]+
char[Math.floor(newTime%36**3 / 36**2)]+
char[Math.floor(newTime%36**2 / 36)]+
char[Math.floor(newTime%36)];
}
console.log(getId());
Thanks to #user956584 this can be be changed to:
function getId() {
//var newTime = parseInt(moment().format("X")) - 1546300800;//seconds since 01/01/2019
var newTime = Math.floor((new Date()).getTime() / 1000) - 1546300800;//seconds since 01/01/2019
return newTime.toString(36);
}
console.log(getId());
I have a Google Sheet with three columns:
- Date and time (timestamp)
- Duration
- Description
I have an script that when I write something in 'Description', inserts in 'Date' the date and time at this moment, and the 'Duration':
function onEdit(e) {
if(e.source.getActiveSheet().getName() == "Sheet2" ) {
var col = e.source.getActiveCell().getColumn();
if(col == 3 ) {
// I'm in column three
var cellTimeStamp = e.range.offset(0,-2); // First column of the same row
var cellTimeDiff = e.range.offset(0,-1); // Second column of the same row
var cellTimePrev = e.range.offset(-1,-2); // First column of the previous row
var timeTimeStamp = new Date();
var iniTime = cellTimePrev.getValue().getTime();
var finTime = timeTimeStamp.getTime() ;
var timeDiff = String(finTime - iniTime) ;
cellTimeStamp.setValue(timeTimeStamp);
cellTimeDiff.setValue(timeDiff); // [***]
}
}
}
When this executes (as an event) in the column of 'Duration' there is NOT something in the format of 'HH:mm:ss'.
But if I remove the last line in this script and adds this formulae in the sheet:
=A3-A2 (in row 3)
=A4-A3 (in row 4)
...
then it works ok.
I'd like to know how to meet the same result but with a script.
Thanks in advance.
timeDiff is the result of finTime - iniTime which are both native date object values, which means we have milliseconds .
converting that in hh:mm:ss is simple math... : 60 seconds in a minute and 60 minutes in an hour...
A simple code could be like this :
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs; // milliSecs are not shown but you can use ms if needed
}
If you prefer formating your string more conventionally (2 digits for each value) don't forget you can use Utilities.formatString() to do so.
example below :
return Utilities.formatString("%02d",hrs) + ':' + Utilities.formatString("%02d",mins) + ':' + Utilities.formatString("%02d",secs);
EDIT
Following your comment :
Spreadsheets are smarter than you think, you can try the code below and you will see that the result is actually a time value.(check by double clicking on it)
function test() {
var sh = SpreadsheetApp.getActiveSheet();
var t1 = sh.getRange('a1').getValue().getTime();
var t2 = sh.getRange('b1').getValue().getTime();
sh.getRange('c1').setValue(msToTime(t1-t2)).setNumberFormat('hh:mm:ss');
}
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs; // milliSecs are not shown but you can use ms if needed
}
note that setNumberFormat('hh:mm:ss') is optional, it's only there to force the spreadsheet to display hour:min:sec format but automatic mode works as well.
I am trying to calculate the time difference between 2 date time strings.
I have 2 inputs where the input string is something like this "1:00 PM" and the second one "3:15 PM". I want to know the time difference. So for the above example I want to display 3.15
What I have done:
Converted the time to a 24 hours format. So "1:00 PM" becomes "13:00:00"
Appended the new time to a date like so: new Date("1970-1-1 13:00:00")
Calculated the difference like so:
Code:
var total = Math.round(((new Date("1970-1-1 " + end_time) -
new Date("1970-1-1 " + start_time) ) / 1000 / 3600) , 2 )
But the total is always returning integers and not decimals, so the difference between "1:00 PM" and "3:15 PM" is 2 not 2.15.
I have also tried this (using jQuery, but that is irrelevant):
$('#to_ad,#from_ad').change(function(){
$('#total_ad').val( getDiffTime() );
});
function fixTimeString(time){
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10) sHours = "0" + sHours;
if(minutes<10) sMinutes = "0" + sMinutes;
return sHours + ':' + sMinutes + ':00';
}
function getDiffTime(){
var start_time = fixTimeString($('#from_ad').val());
var end_time = fixTimeString($('#to_ad').val());
var start = new Date("1970-1-1 " + end_time).getTime(),
end = new Date("1970-1-1 " + start_time).getTime();
return parseInt(((start - end) / 1000 / 3600, 10)*100) / 100;
}
But the total_ad input is displaying only integer values.
How can I fix this problem?
Math.round rounds to the nearest integer, multiply and divide instead
var start = new Date("1970-1-1 " + start_time).getTime(),
end = new Date("1970-1-1 " + end_time).getTime();
var total = (parseInt(((start-end) / 1000 / 3600)*100, 10)) / 100;
FIDDLE
When you take the time 15:15:00 and subtract 13:00:00, you're left with 2.15 hours, not 3.15, and this example would return 2.15 even without making sure there is only two decimals, but for other times that might not be the case.
You could also use toFixed(2), but that would leave you with 3.00 and not 3 etc.
This is how I calculate it:
calculateDiff();
function calculateDiff(){
_start = "7:00 AM";
_end = "1:00 PM";
_start_time = parseAMDate(_start);
_end_time = parseAMDate(_end);
if (_end_time < _start_time){
_end_time = parseAMDate(_end,1);
}
var difference= _end_time - _start_time;
var hours = Math.floor(difference / 36e5),
minutes = Math.floor(difference % 36e5 / 60000);
if (parseInt(hours) >= 0 ){
if (minutes == 0){
minutes = "00";
}
alert(hours+":"+minutes);
}
}
function parseAMDate(input, next_day) {
var dateReg = /(\d{1,2}):(\d{2})\s*(AM|PM)/;
var hour, minute, result = dateReg.exec(input);
if (result) {
hour = +result[1];
minute = +result[2];
if (result[3] === 'PM' && hour !== 12) {
hour += 12;
}
}
if (!next_day) {
return new Date(1970, 01, 01, hour, minute).getTime();
}else{
return new Date(1970, 01, 02, hour, minute).getTime();
}
}
I need to be able to compare the number of whole days between two dates in ActionScript, is this possible?
I'd like to test if one date is 7 days or less after today, and if so is it one day or less (if it's before today this also counts).
The workaround I have in place is using the .time part of the date field:
// Get the diffence between the current date and the due date
var dateDiff:Date = new Date();
dateDiff.setTime (dueDate.time - currentDate.time);
if (dateDiff.time < ( 1 * 24 * 60 * 60 * 1000 ))
return "Date is within 1 day");
else if (dateDiff.time < ( 7 * 24 * 60 * 60 * 1000 ))
return "Date is within 7 days");
As I say - this is only a workaround, I'd like a permanent solution to allow me to check the number of whole days between 2 dates. Is this possible?
Thanks
var daysDifference:Number = Math.floor((dueDate.time-currentDate.time)/(1000*60*60*24));
if (daysDifference < 2)
return "Date is within 1 day";
else if (daysDifference < 8)
return "Date is within 7 days";