Subtracting minutes from a timestamp in msexcel - excel

I am extracting a timestamp from a cell in the format like Tue Nov 06 07:33:00 UTC 2018. Now, using vbscript code or vba code I want to subtract some minutes from the above mentioned timestamp. How can I achieve that?

split(split("Tue Nov 06 07:33:00 UTC 2018",":")(1),":")(0)
Will give you the minutes on their own. You can assign the splits to arrays, then rejoin with the correct minutes using `join
Something like so
Public Function addToTimeStamp(strTimeStamp As String, lngMinutes As Long) As String
Dim a() As String
a = Split(strTimeStamp, " ")
a(3) = DateAdd("n", lngMinutes, a(3))
addToTimeStamp = Join(a, " ")
End Function

Without going into VBA, you could separate the time stamp from the date, then work on the time stamp and adjust the date accordingly.
Assuming your dates are in the column A and that the timestamp always take the same structure, starting from row number 2
So first you create a column where there is only the time stamp, that is column B:
=MID(A2,FIND("UTC",A2)-9,8)
07:33:00
This first finds the position of "UTC" within the string then extract 8 characters starting from 9 characters to the left (accounting for the space between the time and "UTC").
Already there you can work on the minutes/hours/seconds.
Hours:
=NUMBERVALUE(LEFT(B2,2))
07
Minutes:
=NUMBERVALUE(Mid(B2,4,2))
33
Seconds:
=NUMBERVALUE(Right(B2,2))
00
You can also extract the date part of the time stamp using the same logic. Column C:
=MID(A2,FIND(B2,A2)-11,10)
Tue Nov 06
Finally you can also combine all of that into an Excel date and do your operations directly on the resulting number (This will ensure that you get a new valid date which account for incrementing/decrementing hours/days/months/years, it will also automatically account for leap years.)
Final date, including the time stamp, Column D:
=DATEVALUE(MID(A2,FIND(B2,A2)-3,2)&"-"&MID(A2,FIND(B2,A2)-7,3)&"-"&RIGHT(A2,4))+NUMBERVALUE(LEFT(B2,2))/24+NUMBERVALUE(MID(B2,4,2))/(24*60)+NUMBERVALUE(RIGHT(B2,2))/(24*60*60)
43410.3145833333
On this final number you can simply increase/decrease the number of minutes by adding it directly to it. The unit of this number is "days" so one minute is equal to 1/(24*60) and one hour is 1/24. Example of removing 33 minutes:
=D2 - 33/(24*60)
43410.2916666667
Changing the formatting to [dd/mm/yyyy hh:mm] will then result in:
06/11/2018 07:00:00

Related

How to convert UTC to PST in Excel for day and time formats?

In excel, I have a cell which is
13 05:58:57
which represents day 13, 5 am, 58 minutes, 57 seconds in UTC time.
I would like to convert to PST, which should be
12 10:58:57
which is day 12, 10 pm, 58 minutes, 57 seconds.
The day is just a day of the month. Is there a way to do this quickly in excel?
Excel stores date_times as numbers, where each day is 1, and the decimal part of the number is the time (so 0.25 is 6 hours, and 0.7 is 16 hours + 48 minutes)
Time 0 is the beginning of 1899/12/31, so =today() formatted as a decimal currently shows me as 44730.4556, being 44730 days since 1899 and almost eleven a.m.
Once you have your data in that format it is trivial to E.g.:
subtract 7 hours = A2 - 7/24
add 2 days 6 hours and 15 minutes = A2 + 2 + 6/24 + 15/24/60
find the difference between two date_times
So you want to get the input data into that form, from which point you just use formatting.
To see where you are going, enter in A1 = now(), in B1 =A1, in C1 = B1.
Change the format on B1 - Right Click | Format Cells | Custom | yyyy-mm-dd hh:mm:ss.
Then in C1 try changing to a format you want: dd hh:mm:ss AM/PM.
For a full list of options see https://support.microsoft.com/en-au/office/format-numbers-as-dates-or-times-418bd3fe-0577-47c8-8caa-b4d30c528309
I will assume that your data starts at A4, but I can't tell what is actually stored in the cell, as opposed to what it displays.
If your input data is actually already a date_time (what does it look like if you format is as a decimal?) all you need to do is =A4-7/24.
If your input data is actually a string, then separate it into day, hour, minute, second in C, D, E, F.
If single-digit days have leading zeros then just =left(A4,2) then =mid(A4,4,2) etc.
If there are no leading zeros put in column B =find(" ",A4) and point the lefts and mids to that intermediate result.
Then in G put = C4 + D4/24 + E4/24/60 + F4/24/60/60 so you have the input data as an Excel-formatted time.
And subtract the 7 hours difference with =G4-7/24
P.S. If you need to cope with month-ends and DST then you need to add year and month to the data in G - currently it has date_times in January 1899.

How do I get a string value of the 5 digit serial date format from a cell into my script?

I have a formula in a cell that is doing a vlookup to another sheet by combining the values of two cells on my spreadsheet. It's a table of names on the left and dates up top. I'm combining the name and date values into a single string value and using that as by vlookup key value, which works great. Now I need to basically do the same thing in my google script, but the date value has me at a loss. In the vlookup cell formula, the date value is the 5 digit date serial code. However when I combine the two cell values in my script, I cannot get the same 5 digit serial code out of the cell. I have tried all conversions of number, string, text, ect. What function can I use to get this 5 digit date value as a string in my script?
function serialDatevalue(){
var WB = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var NewDate = new Date();
var NewDate = WB.getRange('B1').getValue();
var JSdate = WB.getRange('B1').getValue();
Browser.msgBox(Number(NewDate));
// Some others that I have tried
// var JSdate = Date.parse(DateValue);
// var JSdate = Number(DateValue);
// var JSdate = Utilities.formatDate(DateValue, 'PST', '%');
}
for example, April 13, 2019 = 43568. I want to get this 5 digit value as a string.
I keep getting 'Sat Apr 13 2019 00:00:00 GMT-0700 (PDT)', or other longer integer values.
Please help.
From Tanaike's answer to Getting the number equalent of duration using GAS
var serialNumber = (dateObject.getTime() / 1000 / 86400) + 25569; // Reference: https://stackoverflow.com/a/6154953
The easier way to get the serialized number corresponding to a certain cell date value in Google Sheets is by using a the built-in Google Sheets function [TO_PURE_NUMBER][1]. This because Google Sheets and JavaScript, which is used by Google Apps Script, used different epoch (reference date used as 0 for the serialized numbers) and use different time units.
From https://developers.google.com/sheets/api/guides/concepts#datetime_serial_numbers
Date/Time serial numbers
Google Sheets, like most other spreadsheet
applications, treats date/time values as decimal values. This lets you
perform arithmetic on them in formulas, so you can increment days or
weeks, add or subtract two date/times, and perform other similar
operations.
Google Sheets uses a form of epoch date that is commonly used in
spreadsheets. The whole number portion of the value (left of the
decimal) counts the days since December 30th 1899. The fractional
portion (right of the decimal) counts the time as a fraction of one
day. For example, January 1st 1900 at noon would be 2.5, 2 because
it's two days after December 30th, 1899, and .5 because noon is half a
day. February 1st 1900 at 3pm would be 33.625.
Note that Google Sheets correctly treats the year 1900 as a common
year, not a leap year.
By the other hand, JavaScript use January 1, 1970 00:00 UTC as the epoch date and use milliseconds as the unit.
A word of caution: Custom code to make serialized number conversions from one to the other should consider if the spreadsheet and the Google Apps Script are using the same timezone or not.
Related
How to read value of fetched cell data as date google sheets API
Getting the number equalent of duration using GAS

Excel 2013 Date time difference

I have a column with date and time for start (IN) and end (OUT) and I want to calculate the difference in days.
Date: IN Time: IN Date: OUT Time: OUT
24/07/2018 12:15:00 26/07/2018 06:11:00
I combine them into date time IN and OUT by using:
E1=TEXT(A2,"dd/mm/yy ")&TEXT(B2,"hh:mm:ss")
F1=TEXT(C2,"dd/mm/yy ")&TEXT(D2,"hh:mm:ss")
But I am unable to find any working code for the difference in number of hours.
TEXT will convert your dates and times into text (strangely enough).
Adding the date and time will return a date/time value so you could use:
=SUM(C2:D2)-SUM(A2:B2) to return 1.74722222
(edit: if you then give the cell a custom number format of d:h:mm it will display 1:17:56 or 1 day, 17 hours, 56 minutes).
(EDIT AGAIN: Sorry, only just seen you want it in hours. Give the cell a custom number format of [hh]:mm. The square brackets tells it to count over 24 hours. This will return 41:56).
or
=DATEDIF(SUM(A2:B2),SUM(C2:D2),"d") to return 2.
or if you just want days from the dates you could just use
=C2-A2 to return 2.
Dates and times in Excel are just numbers - no need to complicate things by turning them to text.
= (F1 - E1) * 24
Rather easly :)

How to count hours in excel

I have xls file in following format
Name 1 2 3 4
John 09:00-21:00 09:00-21:00
Amy 21:00-09:00 09:00-21:00
Where 1,2,3,4 and so on represent days of current month,
09:00-21:00 - working hours.
I want to calculate salary based on the following conditions:
09:00-21:00 - 10$/hour
21:00-00:00 - 15$/hour
00:00-03:00 - 20$/hour
etc.
and so on (every hour can have it's own cost, for example 03:00-04:00 - 20$/hour, 04:00-05:00 - 19$/hour, etc.)
How can i accomplish this using only Excel (functions or VBA)?
P.S. Easy way: export to csv and process in python/php/etc.
Here is a non-VBA solution. It's a pretty nasty formula, but it works. I am sure it could be made even easier to use and understand with some more ingenuity:
Assuming the spreadsheet is set up like this:
Enter this formula in cell G1 and drag down for your data set:
=IF(ISBLANK(B2),"",IF(LEFT(B2,2)<MID(B2,FIND("-",B2)+1,2),SUMIFS($P$2:$P$24,$Q$2:$Q$24,">="&LEFT(B2,2),$Q$2:$Q$24,"<="&MID(B2,FIND("-",B2)+1,2)),SUMIF($Q$2:$Q$24,"<="&MID(B2,FIND("-",B2)+1,2),$P$2:$P$24)+SUMIF($Q$2:$Q$24,">="&LEFT(B2,2),$P$2:$P$24)))
To explain the formula in detail:
IF(ISBLANK(B2),"" will return a empty string if there is no time for a given person / day combination.
LEFT(B2,2) extracts the start-time into an hour.
Mid(B2,Find("-",B2)+1,2) extracts the end-time into an hour.
IF(LEFT(B2,2)<MID(B2,FIND("-",B2)+1,2) will check if the start-time is less than the end-time (meaning no over-night work). If the start-time is less than the end-time, it will use this formula to calculate the total cost per hour: SUMIFS($P$2:$P$24,$Q$2:$Q$24,">="&LEFT(B3,2),$Q$2:$Q$24,"<="&MID(B3,FIND("-",B3)+1,2))
If the start-time is higher than the end-time (meaning overnight work), it will use this formula to calculate: SUMIF($Q$2:$Q$24,"<="&MID(B3,FIND("-",B3)+1,2),$P$2:$P$24)+SUMIF($Q$2:$Q$24,">="&LEFT(B3,2),$P$2:$P$24)
The use of the Find("-",[cell]) splits the start-and- end times into values excel can use to do math against the Time / Cost table.
The formula in column Q of the Time / Cost table is =VALUE(MID(O2,FIND("-",O2)+1,2)) and turns the ending hour to consider the cost into a value Excel can use to add, instead of having the text from your original source format.
Do this in VBA! It is native to excel and is easy to learn. Functionally, I would loop through the table, write a function to calculate the dollars earned based on the info given. If you want your results to be live updating (like a formula in excel) you can write a user defined function. A helpful function might be an HoursIntersect function, as below:
Public Function HoursIntersect(Period1Start As Date, Period1End As Date, _
Period2Start As Date, Period2End As Date) _
As Double
Dim result As Double
' Check if the ends are greater than the starts. If they are, assume we are rolling over to
' a new day
If Period1End < Period1Start Then Period1End = Period1End + 1
If Period2End < Period2Start Then Period2End = Period2End + 1
With WorksheetFunction
result = .Min(Period1End, Period2End) - .Max(Period1Start, Period2Start)
HoursIntersect = .Max(result, 0) * 24
End With
End Function
Then you can determine the start and end time by splitting the value on the "-" character. Then multiply each payment schedule by the hours worked within that time:
DollarsEarned = DollarsEarned + 20 * HoursIntersect(StartTime, EndTime, #00:00:00#, #03:00:00#)
DollarsEarned = DollarsEarned + 10 * HoursIntersect(StartTime, EndTime, #09:00:00#, #21:00:00#)
DollarsEarned = DollarsEarned + 15 * HoursIntersect(StartTime, EndTime, #21:00:00#, #00:00:00#)
I have a method that uses nothing but formulas. First create a lookup table which contains every hour and rate in say columns K & L, something like this:
K L
08:00 15
09:00 10
10:00 10
11:00 10
12:00 10
13:00 10
14:00 10
15:00 10
16:00 10
17:00 10
18:00 10
19:00 10
20:00 10
21:00 15
22:00 15
23:00 15
Make sure you enter the hours as text by entering a single quote before the digits.
Then if your hours were in cell B2 you could then use this formula to calculate the total:
=SUM(INDIRECT("L"&MATCH(LEFT(B2,5),K2:K40,0)&":L"&MATCH(RIGHT(B2,5),K2:K40,0)))
All the formula is doing is getting the left and right text of your work time, using MATCH to find their positions in the lookup table which is used to create a range address which is then passed to SUM via the INDIRECT function.
If you need to worry about minutes all you need to do is create a bigger lookup table which holds every minute of the day. You may need to add some extra logic if your work days span midnight.

Numerical month to character month in excel

Is there a pre-installed function that directly converts 08 to Aug, 10 to Oct?
Currently I use text(date(0,have,1),"mmm").
You could simplify like this: =TEXT("8/0","mmm").
Update
I've come up with a new technique: =TEXT(number * 30,"mmm"):
How it works
Dates are stored as numbers in Excel. The number 1 is the date Jan 1, 1900; 2 is Jan 2, 1900; etc.
The 30th day in 1900 is in January; the 60th day is in February; the 90th day is in March.
Every multiple of 30 between 30 and 360 is in a different month. So we can simply multiply 30 by a number between 1 and 12, and the TEXT function will give us the month.
You can use
MonthName(yourmonthNumber)
or
MonthName(yourmonthNumber, True) 'to abbreviate the name
Or did you mean a worksheet function?

Resources