Date to Excel timestamp - date

I need to calculate an Excel "timestamp" (reference 01.01.1900, not 1970 like the unix timestamp) ; here what I did:
Date mydate = new Date();
unixTimestamp = mydate.getTime() / 1000;
excelTimestamp = unixTimestamp / 86400;
def startPoint= new GregorianCalendar(1900, Calendar.JANUARY, 0, 0,0,0).time;
TimeZone tz = TimeZone.getTimeZone("Europe/Berlin");
howmany = tz.getOffset(new Date().getTime()) / 1000;
excelTimeStamp = (unixTimestamp - startPoint.time/1000) / 86400;
the latter returns 1 day less, and 1 hour more... what did I wrong ?

the solution was MUCH easier:
Date mydate = new Date();
unixTimestamp = mydate.getTime() / 1000;
TimeZone tz = TimeZone.getTimeZone("Europe/Berlin");
howmany = tz.getOffset(new Date().getTime()) / 1000;
excelTimeStamp = 25569 + (unixTimestamp+howmany)/86400;

Related

Date difference in hours - Angular 2

How can I get difference in hours between two dates in angular2? I don't want to use external libs like moment.js.
Having, for example: incidentTime = '2017-03-05 11:26:16 AM' and creationTime = '2017-03-06 12:26:16 AM'
let time = +params.data.incidentTime - +params.data.creationTime;
console.log("time: " + time);
It should return 25 hours, but It returns NaN.
This should do the job:
const date1 = params.data.incidentTime;
const date2 = params.data.creationTime;
const diffInMs = Date.parse(date2) - Date.parse(date1);
const diffInHours = diffInMs / 1000 / 60 / 60;
console.log(diffInHours);
Use Math.floor to round the result down, or Math.ceil to round it up
parse the date type parameters to javascript's Date type.
let date1 = new Date(params.data.incidentTime).getTime();
let date2 = new Date(params.data.creationTime).getTime();
let time = date1 - date2; //msec
let hoursDiff = time / (3600 * 1000);
Try this:-
let time:any = new Date("2017-03-05 11:26:16").getHours();
let date2:any = new Date("2017-03-06 12:26:16").getHours();
console.log(time -date2, time, date2, "sdfsd");
but It returns NaN
this is because you are using + sign before date which is converting youtr date into number format so returning NAN(not a number)

How can I go backward in time using datenum?

I have these two dates.
startTime = '4/2/2004 12:45'
endTime = '4/3/2004 18:15'
I want to find the time that is exactly 1.5*(startTime-endTime) in the past. And in the format I have rather than datenum. The time progresses in 5 minute steps in my dataset.
I am doing this, but not sure where to go from where:
startTime = datenum('4/2/2004 12:45');
endTime = datenum('4/3/2004 18:15');
Finally, I do something like this to generate filenames for some batch processing.
for l = 1:timeSteps
precipFileNames{l} = strcat(fileparts(refFile), filesep,'RATE.',datestr(startTime, 'yyyymmdd.hhMMss'), '.tif');
startTime = addtodate(startTime, 5, 'minute');
end
You were close. You can use at least two different approaches, datetime or datenum.
Using datenum:
startTime = datenum('4/2/2004 12:45');
endTime = datenum('4/3/2004 18:15');
anotherTime = now;
inPast = anotherTime + (startTime - endTime) * 1.5;
datestr(inPast, 'yyyymmdd.hhMMss');
Or, using datetime:
startTime = datetime('4/2/2004 12:45', 'Format', 'MM/dd/uuuu HH:mm')
endTime = datetime('4/3/2004 18:15', 'Format', 'MM/dd/uuuu HH:mm')
anotherTime = datetime;
inPast = anotherTime + (startTime - endTime) * 1.5;
datestr(inPast, 'yyyymmdd.hhMMss');
startTime = startTime + minutes(5);

how can i calculate the difference between two dates from the user input?

This is my code so far:
import datetime
from time import strptime
leapyear = 0
isValid = False
while not isValid:
in_date = input(" Please in put a year in the format dd/mm/yyyy ")
try:
d = strptime(in_date, '%d/%m/%Y')
isValid=True
except:
print ("This is not in the right format")
date = datetime.date.today().strftime("%d/""%m/""%Y")
in_date = in_date.split('/')
date = date.split('/')
in_date = [int(i) for i in in_date]
date = [int(i) for i in date]
date_f = [str(i) for i in date]
date_f = '/'.join(date_f)
in_date_f = [str(i) for i in in_date]
in_date_f = '/'.join(in_date_f)
newdate = []
in_date[0], in_date[2] = in_date[2], in_date[0]
date[0], date[2] = date[2], date[0]
z = "/"
if in_date > date:
newdate.insert((0),(in_date[2] % date[2]))
newdate.insert((1),(in_date[1] % date[1]))
newdate.insert((2),(in_date[0] % date[0]))
print("Current Date:", date_f)
print("you are:", newdate[2],"year(s)",newdate[1],"month(s) and",newdate[0],"days away from:",in_date_f)
else:
print("Please input a date thats higher than todays.")
At the moment i have taken today's date and then taken away that from the user input date which has to be higher than the current date. but this gives the wrong answer because it hasnt taken in the fact of the days in a month the and the months in a year.
how would i go about doing that?
datetime objects are subtractable and comparable, so there is no problem in doing:
userDate = strptime(in_date, '%d/%m/%Y')
if userDate > datetime.datetime.today():
# ...
or
if userDate.date() > datetime.datetime.today().date():
# ....
or to calculate the difference:
diff = userDate - datetime.datetime.today()

How to calculate the time difference between 2 date time values

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();
}
}

GWT converting current date to GMT

I am converting the current date to GMT time.
The result is in-consistent, due to this my date time calculations are going worng.
DateTimeFormat df = DateTimeFormat.getFormat("dd MMM yyyy hh:mm:ss");
String gmtStr = new Date().toGMTString().replace("GMT", "").trim();
long deptime= depTime - df.parse(gmtStr).getTime();
deptime = deptime / 1000;
seconds = (deptime % 60);
minutes = (deptime % 3600) / 60;
hours = (deptime / 3600);
Not sure what the best way is, but you could use the getTimezoneOffsert:
final Date gmtDate = new Date();
final Date offDate = new Date(gmtDate.getTime() + gmtDate.getTimezoneOffset() * 60 * 1000);
The offDate when displayed with DateTimeFormat.getFormat(PredefinedFormat.DATE_TIME_LONG) will still show the utc/gmt offset, because basically you have create a new time in the current timezone, but it matches the time of the GMT time and the long value returned from getTime() will be the number of milliseconds you can use in your calculation.