Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I recently found the following code online that gives FFXIV's in-game time (Eorzea time):
var E_TIME = 20.5714285714;
var global = {
utcTime: null,
eorzeaTime: null
};
window.setInterval(updateClock, Math.floor(1000 * 60 / E_TIME));
function updateClock() {
global.utcTime = new Date().getTime();
var eo_timestamp = Math.floor(global.utcTime * E_TIME);
global.eorzeaTime = new Date();
global.eorzeaTime.setTime(eo_timestamp);
showTime();
}
function showTime() {
var d = new Date();
d.setTime(global.eorzeaTime);
var eTime = document.getElementById('e-time');
var hours = d.getUTCHours();
var ampm = hours > 11 ? "PM" : "AM";
if(hours > 12)
hours -= 12;
hours = padLeft(hours);
var minutes = d.getUTCMinutes();
minutes = padLeft(minutes);
eTime.innerHTML = hours + ":" + minutes + " " + ampm;
}
function padLeft(val){
var str = "" + val;
var pad = "00";
return pad.substring(0, pad.length - str.length) + str;
}
updateClock();
NOTE: I take no credit in that code, I am not the original coder and it was found here: http://jsfiddle.net/jryansc/6r85j/
What I would like to do is get something that does the same result in C# (time wise), unfortunately I am new to programming and I know only some C# at the moment. This is why I am asking for help, I tried to manipulate DateTime and TimeSpan in C# but it does not seem as easy as it is in JavaScript (according to the code above).
Can someone help me out to convert the code please?
All the help is greatly appreciated.
Assuming your question is 'How do I calculate Eorzea time in C#':
Javascript's Time class is based around Epoch Time (the amount of time that has elapsed since 00:00 1/1/1970). When you multiply the Time() object, you're multiplying the number of seconds that have elapsed since that date.
.NET's DateTime class doesn't support the simple multiply operator Javascript does, but it's easy to duplicate. You need to calculate how many ticks, seconds, minutes (whichever you like) have elapsed since 1/1/1970, then multiply that number by 20.5714285714, and convert back to a DateTime.
In my example, I'm using ticks instead of seconds.
const double EORZEA_MULTIPLIER = 3600D / 175D; //175 Earth seconds for every 3600 Eorzea seconds
// Calculate how many ticks have elapsed since 1/1/1970
long epochTicks = DateTime.UtcNow.Ticks - (new DateTime(1970, 1, 1).Ticks);
// Multiply that value by 20.5714285714...
long eorzeaTicks = (long)Math.Round(epochTicks * EORZEA_MULTIPLIER);
var eorzeaTime = new DateTime(eorzeaTicks);
To make things even easier, you could created a DateTime extension method:
public static class EorzeaDateTimeExtention
{
public static DateTime ToEorzeaTime(this DateTime date)
{
const double EORZEA_MULTIPLIER = 3600D/175D;
long epochTicks = date.ToUniversalTime().Ticks - (new DateTime(1970, 1, 1).Ticks);
long eorzeaTicks = (long)Math.Round(epochTicks * EORZEA_MULTIPLIER);
return new DateTime(eorzeaTicks);
}
}
Which will allow you to convert ANY date to Eorzea time by simply:
var eorzeaTimeNow = DateTime.Now.ToEorzeaTime();
or
var eorzeaSpecificTime = new DateTime(2014,5,12,5,0,0).ToEorzeaTime();
TIP: Make sure your PC clock is set accurately ... I found this code was a few minutes out until I realised that my clock was several seconds behind. :)
Related
I need to count the remaining time in hours between today or actual date/time and a specific end date at 00:00 hrs.
I tried in this fiddle, but I get the counting of one month more than it should be.
https://jsfiddle.net/alonsoct/52ts89mz/
var endTime = new Date(2019,10,18,0,0,0) / 1000;
function setClock() {
var elapsed = new Date() / 1000;
var totalTime = endTime - elapsed;
var hr = parseInt(totalTime / 3600)
var min = parseInt(totalTime / 60) % 60;
var sec = parseInt(totalTime % 60, 10);
var result = hr + " hours, " + min + " minutes " + sec + " seconds";
document.getElementById('timeRemaining').innerHTML = result;
setTimeout(setClock, 1000);
}
setClock();
If I enter one month less in the "endTime" variable I get the correct result in hours count, but this is not fine I need to enter the real end date without the need to subtract one month.
Thanks
The code below is mostly your code with one change. I changed the input for endTime to an ISO format and omitted the time Zone. This, in theory, will default to your browser's timezone. I tested on your linked and it worked. Here is some additional information https://www.w3schools.com/js/js_date_formats.asp
var endTime = new Date("2019-10-18T00:00:00") / 1000;
function setClock() {
var elapsed = new Date() / 1000;
var totalSec = endTime - elapsed;
var h = parseInt( totalSec / 3600 )
var m = parseInt( totalSec / 60 ) % 60;
var s = parseInt(totalSec % 60, 10);
var result = h + " hours, " + m + " minutes " + s + " seconds";
document.getElementById('timeRemaining').innerHTML = result;
setTimeout(setClock, 1000);
}
setClock();
Here is a working solution with Vanilla JS:
var calcTime = setInterval(function(){
date_future = new Date(2019,10,18,0,0,0)
date_now = new Date();
seconds = Math.floor((date_future - (date_now))/1000);
minutes = Math.floor(seconds/60);
hours = Math.floor(minutes/60);
days = Math.floor(hours/24);
hours = hours-(days*24);
minutes = minutes-(days*24*60)-(hours*60);
seconds = seconds-(days*24*60*60)-(hours*60*60)-(minutes*60);
It's pretty easier with JQuery → http://hilios.github.io/jQuery.countdown/examples/show-total-hours.html
JavaScript counts months from 0 to 11.
January is 0. December is 11.
I think you were thinking that endTime will be October 18th, 2019 but actually it's November 18th, 2019.
You can see more relevant information here.
https://www.w3schools.com/js/js_dates.asp
Thanks.
If between the start-datetime and end-datetime a change takes place in winter / summertime remember to make summertime/wintertime adjustments
(if you get these values from e.g. an api:) if the startdate is specified by a client in location x and enddate is specified in location y, you have take into account that the startdate could potentially be in 00:00:00+14:00 timezone and end the endate in max -14 timezone.
if you only present 2 timeboxes: time 1 and time 2, you can map these anywhere on a 52 hours time-scale: -14 , +14 and the 24 hours gmt timescale where you then would normalize to. ( 0:00 could mean i am in Samoa +14, 14 hours ahead of the end of GMT 23:59:59 (14 further) or ahead of GMT 0:00 (14+24 further). Then there are countries which make local time decisions e.g. in India with +5.5 UTC or Burma +6.5 or newfoundland -3.5.
Since this is stackexchange and people will copy and paste these examples in their applications even if these applications are "on the internet" and so DO have users from every location in the world.
Therefore ... use a library: https://momentjs.com/ ; Get hours difference between two dates in Moment Js they have a helper https://momentjs.com/docs/#/displaying/to/ and see also: Moment.js - How To Detect Daylight Savings Time And Add One Day
You can see the same bug on https://www.timeanddate.com/countdown but they added in words : https://www.timeanddate.com/countdown/one-hour-offwintertijd (and they assume the end datetime is in the same location as the countdown datetime)
I am working on a date comparison and I am trying to calculate and display the difference between two dates in a format of dates, hours, minutes...
Date values are stored in the DB like:
EndDate : 2018-11-29 10:49:49.9396033
PurchaseDate: 2018-11-29 10:49:07.4154497
And in my Angular component, I have:
let result = new Date(res.endDate).valueOf() - new Date(res.purchaseDate).valueOf();
This leads to: 42524 which I am not sure what it represents.
I wonder what is the proper way to calculate the time difference between two dates and also how can I display the result in a proper and readable way.
Any help is welcome
Working Example in codepen
let endDate = new Date("2018-11-29 10:49:07.4154497");
let purchaseDate = new Date("2018-11-29 10:49:49.9396033");
let diffMs = (purchaseDate - endDate); // milliseconds
let diffDays = Math.floor(diffMs / 86400000); // days
let diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours
let diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
console.log(diffDays + " days, " + diffHrs + " hours, " + diffMins + "
minutes");
You can use the getTime() method to get the difference time in milliseconds
let time = purchaseDate.getTime() - endDate.getTime();
You can then format the date as you want with the DatePipe librairy : https://angular.io/api/common/DatePipe
Well, there are pure javascript way of doing it like in Check time difference in Javascript
or you can reuse the efforts put in by engineers who delevloped moment.js. In moment.js, there is a concept called duration whose link is - https://momentjs.com/docs/#/durations/
and you can even find the difference in duration by referencing docs here - https://momentjs.com/docs/#/durations/diffing/
This question already has answers here:
Check time difference in Javascript
(19 answers)
Closed 5 years ago.
I need to compare two different datetime strings (formed: YYYY-MM-DD'T'HH:mm).
Here are the datetime strings:
var a = ("2017-05-02T10:45");
var b = ("2017-05-02T12:15");
I've sliced the dates out of them so I only need the time (formed: HH:mm).
var now = a.slice(11, 16);
var then = b.slice(11, 16);
// now = 10:45
// then = 12:15
Is there any way I could get the difference between these two times?
Result should look like this:
1 hour 30 minutes
Also if the dates are different is there any easy solution to get the date difference too?
Use javascript Date:
var a = ("2017-05-02T10:45");
var b = ("2017-05-02T12:15");
var milliseconds = ((new Date(a)) - (new Date(b)));
var minutes = milliseconds / (60000);
This should get you started:
d1 = new Date(Date.parse("2017-05-02T10:45"));
d2 = new Date(Date.parse("2017-05-02T12:15"));
var getDuration = function(d1, d2) {
d3 = new Date(d2 - d1);
d0 = new Date(0);
return {
getHours: function(){
return d3.getHours() - d0.getHours();
},
getMinutes: function(){
return d3.getMinutes() - d0.getMinutes();
},
getMilliseconds: function() {
return d3.getMilliseconds() - d0.getMilliseconds();
},
toString: function(){
return this.getHours() + ":" +
this.getMinutes() + ":" +
this.getMilliseconds();
},
};
}
diff = getDuration(d1, d2);
console.log(diff.toString());
or use momentjs because, 1. it is well tested and bugs are tracked. 2. Coding from scratch is a fun learning experience but if you are in a corporate enviroment, coding from scratch will waste time (and thus money).
i have a lib to make this simple:
wiki:https://github.com/jiangbai333/Common-tools/wiki/format
code:https://github.com/jiangbai333/Common-tools/blob/dev/string/string.js
include string.js in your file, Then:
var temp = "short-stamp".format(+new Date("2017-05-02T12:15")) - "short-stamp".format(+new Date("2017-05-02T10:45"));
console.log(parseInt(temp / 3600), "hour", parseInt(temp % 3600 / 60), "minutes")
I have a quiz program written in vanilla JS. It is supposed to log the time it takes to complete it.
What I would like to achieve is how long it takes for the user to answer the questions by subtraction two variables (strings). If it is even possible.
When the user has stated his name and presses a button "STart Quiz" the currrent time is logged in localstorage like so:
var storeName;
var d = new Date();
var h = getHours();
var m = getMinutes();
var s = getSeconds();
var startTime = h + ":" + m + ":" + s;
var endTime = h + ":" + m + ":" + s;
var result;
var storage = {
storeName: storeName,
startTime: startTime,
endTime: null,
result: result
};
The tricky part is I do not know how to subtract startTime from EndTime to get the time it took to answer the questions. This quiz is over in minutes, so to use the hour is redundant.
When the user has clicked "submit" answer on the last question I want the time logged in LS as endTime.
I hope I have not been unclear and thank you all in advance very much for your time. Thank you.
Instead of storing string as date, directly store the time in milliseconds. Then you can subtract the start time with end time to figure out the time difference.
var startTime = Date.now();
var storage = {
storeName: storeName,
startTime: startTime,
endTime: null,
result: result
};
Later you can calculate the endTime using Date.now() and subtract that from startTime to get the time difference.
storage.endTime = Date.now();
//difference
var diff = storage.endTime - storage.startTime;
You use your new Date() wrong.
Should be this.
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
console.log(h);
As for futher implementation you should save current time then use timer on click/login. After that substract these two values. Example for seconds. You just devide (and/or take a modulo to go to real minutes at current time) by for example 3600 to get seconds instead of an hour. Or you can use all your variable and subtract the time. On the way if you get problems with addition for example you can get 5 + 3 = 53 instead of 8 you use Number(5) + Number(3) to do adition instead of concat. Good luck :P
EDIT: also to get time from your string. With split you get array of value.
var test = h + ":" + m + ":" + s;
console.log(test.split(":"));
I need to write JavaScript that's going to allow me to compare two ISO timestamps and then print out the difference between them, for example: "32 seconds".
Below is a function I found on Stack Overflow, it turns an ordinary date into an ISO formatted one. So, that's the first thing out the way, getting the current time in ISO format.
The next thing I need to do is get another ISO timestamp to compare it with, well, I have that stored in an object. It can be accessed like this: marker.timestamp (as shown in the code below). Now I need to compare those two two timestamps and work out the difference between them. If it's < 60 seconds, it should output in seconds, if it's > 60 seconds, it should output 1 minute and 12 seconds ago for example.
Thanks!
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'}
var date = new Date();
var currentISODateTime = ISODateString(date);
var ISODateTimeToCompareWith = marker.timestamp;
// Now how do I compare them?
Comparing two dates is as simple as
var differenceInMs = dateNewer - dateOlder;
So, convert the timestamps back into Date instances
var d1 = new Date('2013-08-02T10:09:08Z'), // 10:09 to
d2 = new Date('2013-08-02T10:20:08Z'); // 10:20 is 11 mins
Get the difference
var diff = d2 - d1;
Format this as desired
if (diff > 60e3) console.log(
Math.floor(diff / 60e3), 'minutes ago'
);
else console.log(
Math.floor(diff / 1e3), 'seconds ago'
);
// 11 minutes ago
I would just store the Date object as part of your ISODate class. You can just do the string conversion when you need to display it, say in a toString method. That way you can just use very simple logic with the Date class to determine the difference between two ISODates:
var difference = ISODate.date - ISODateToCompare.date;
if (difference > 60000) {
// display minutes and seconds
} else {
// display seconds
}
I'd recommend getting the time in seconds from both timestamps, like this:
// currentISODateTime and ISODateTimeToCompareWith are ISO 8601 strings as defined in the original post
var firstDate = new Date(currentISODateTime),
secondDate = new Date(ISODateTimeToCompareWith),
firstDateInSeconds = firstDate.getTime() / 1000,
secondDateInSeconds = secondDate.getTime() / 1000,
difference = Math.abs(firstDateInSeconds - secondDateInSeconds);
And then working with the difference. For example:
if (difference < 60) {
alert(difference + ' seconds');
} else if (difference < 3600) {
alert(Math.floor(difference / 60) + ' minutes');
} else {
alert(Math.floor(difference / 3600) + ' hours');
}
Important: I used Math.abs to compare the dates in seconds to obtain the absolute difference between them, regardless of which is earlier.