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")
Related
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. :)
I want to know the difference between to two dates irrespective of year..
For Example : format date/month/year
For example difference of today date to some date lets take 01/06
The expected answer for this will be around 185 days..
I tried below example..Let me know whats wrong with this
var a = moment('06/01','M/D');
console.log(a);
var b = moment();
console.log(b);
var diffDays = b.diff(a, 'days');
alert(diffDays);
I dont want to use momet.js atmost. If it can be done with javascript its so good for me.
A nice trick could be to set the year to always the same.
var a = moment('2015/06/01','Y/M/D');
console.log(a);
var b = moment().set('year', 2015);
console.log(b);
var diffDays = b.diff(a, 'days');
alert(diffDays);
The problem about your question in general is how to deal with leap years; how the script should know the difference between 2/20 and 3/1 ? You have to consider how to solve this.
Barth Zaleweski is 100% on track with that. If you want to use straight javascript:
var today = new Date();
var otherDate = new Date(today);
otherDate.setMonth(5); // Set the month (on scale from 0 to 11)
otherDate.setDate(1); // set day
var seconds = (otherDate.getTime() - today.getTime()) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
console.log(days);
There are methods for setting hour/minute/second as well, but if you don't do anything they'll be the same as the start, and you can obviously call those same methods on your start time if you don't want to use today.
Can try using this:
var str1 = '06/01', str2 = '02/28', d1, d2, diff;
function setDate(str, date) {
var date = new Date(),
dateParts = str.split('/'),
monthIndex = parseInt(dateParts[0], 10) - 1,
day = parseInt(dateParts[1], 10);
date.setMonth(monthIndex);
date.setDate(day);
return date
}
d1 = setDate(str1);
d2 = setDate(str2);
diff = Math.round(Math.abs((d1 - d2) / (24 * 60 * 60 * 1000)))
console.log(diff) // returns 93
The rounding is due to differences in daylight savings (or other locale time shifts within the year) that can cause decimal values returned.
It is probably better to use UTC for this
If current year is leap year and dates span end of February then Feb 29 would also be counted
DEMO
If it is this year then I am getting a difference of 147 using a library that I have been working on (AstroDate) which doesn't rely on javascript's Date object, it's all done with pure math.
require.config({
paths: {
'astrodate': '//rawgit.com/Xotic750/astrodate/master/lib/astrodate'
}
});
require(['astrodate'], function (AstroDate) {
"use strict";
var diff = new AstroDate("2015","6","1").jd() - new AstroDate("2015","1","5").jd();
document.body.appendChild(document.createTextNode(diff));
});
<script src="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script>
If it was next year, which is a leap year then I am getting 148
require.config({
paths: {
'astrodate': '//rawgit.com/Xotic750/astrodate/master/lib/astrodate'
}
});
require(['astrodate'], function (AstroDate) {
"use strict";
var diff = new AstroDate("2016", "6", "1").jd() - new AstroDate("2016", "1", "5").jd();
document.body.appendChild(document.createTextNode(diff));
});
<script src="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script>
This question already has answers here:
Difference between dates in JavaScript
(8 answers)
Closed 8 years ago.
I am trying to find the difference between two dates. The dates are got with jquery and I am using datejs too. When using datejs it picks up my date as US thinking it is MM/DD/YYYY instead of dd-mm-yyyy. My result for difference is NaN. How do I work this out. Am I miles out or anywhere near close?
var msMinute = 60*1000,
msDay = 60*60*24*1000;
start = $('#reconcile_start_date').val(); // 10-12-2014 | dd-mm-yyyy
end = $('#reconcile_end_date').val(); // 15-12-2014 | dd-mm-yyyy
start = new Date(start);
end = new Date(end);
console.log(Math.floor((end - start) / msDay) + ' full days between ' + end + ' and ' + start);
difference = Math.floor((end - start) / msDay);
if(difference > 30){}
try this:
$(document).ready(function(){
var msMinute = 60*1000;
var msDay = 60*60*24*1000;
var start = '10-12-2014'; // October 12
var statarr=start.split('-');
var end = '12-15-2014'; // December 15
var endarr=end.split('-');
var dstart = new Date(statarr[0]+'/'+statarr[1]+'/'+statarr[2]).getTime();
var dend = new Date(endarr[0]+'/'+endarr[1]+'/'+endarr[2]).getTime();
var diff = parseInt(dend-dstart);
console.log(Math.floor(diff / msDay) + ' full days between ' + end + ' and ' + start);
difference = Math.floor((end - start) / msDay);
if(difference > 30){
}
});
// for UK formate use this:
var start = '12-10-2014'; // October 12
var statarr=start.split('-');
var end = '15-12-2014'; // December 15
var endarr=end.split('-');
var dstart = new Date(statarr[1]+'/'+statarr[0]+'/'+statarr[2]).getTime();
var dend = new Date(endarr[1]+'/'+endarr[0]+'/'+endarr[2]).getTime();
and rest is same.
The issue is around the parsing of the dates, by default JS wont parse the date in the format.
Some more examples on how to convert the date format from UK format can be found (Why does Date.parse give incorrect results?)
More information of the dateString param, formats and browser behaviour - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
See this sample. http://jsbin.com/fayerihipu/2/
$(document).ready(function(){
var msMinute = 60*1000,
var msDay = 60*60*24*1000;
var start = '10-12-2014'; // October 12
var end = '12-15-2014'; // December 15
var dstart = new Date(start).getTime();
var dend = new Date(end).getTime();
var diff = parseInt(dend-dstart);
console.log(Math.floor(diff / msDay) + ' full days between ' + end + ' and ' + start);
difference = Math.floor((end - start) / msDay);
if(difference > 30){
}
});
Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd, and almost all browsers also support yyyy/mm/dd as well.
So you need to do something like this to parse your dates:
var parts = start.split('-');
start = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[0], 10));
//Date uses zero-based month numbers, and so we have to subtract one from the month number
Take a look here for more details.
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.
I have to calculate the difference between 2 timestamps. Also can you please help me with conversion of a string into timestamp. Using plain javascript only. NO JQUERY.
Here's my function:
function clearInactiveSessions()
{
alert("ok");
<c:if test="${not empty pageScope.sessionView.sessionInfo}">
var currentTime = new Date().getTime();
alert("curr:"+currentTime);
var difference=new Date();
<c:forEach items="${pageScope.sessionView.sessionInfo}" var="inactiveSession">
var lastAccessTime = ${inactiveSession.lastUpdate};
difference.setTime(Maths.abs(currentTime.getTime()-lastAccessTime.getTime()));
var timediff=diff.getTime();
alert("timediff:"+timediff);
var mins=Maths.floor(timediff/(1000*60*60*24*60));
alert("mins:"+mins);
if(mins<45)
clearSession(${item.sessionID});
</c:forEach>
</c:if>
}
i am posting my own example try implement this in your code
function timeDifference(date1,date2) {
var difference = date1.getTime() - date2.getTime();
var daysDifference = Math.floor(difference/1000/60/60/24);
difference -= daysDifference*1000*60*60*24
var hoursDifference = Math.floor(difference/1000/60/60);
difference -= hoursDifference*1000*60*60
var minutesDifference = Math.floor(difference/1000/60);
difference -= minutesDifference*1000*60
var secondsDifference = Math.floor(difference/1000);
console.log('difference = ' +
daysDifference + ' day/s ' +
hoursDifference + ' hour/s ' +
minutesDifference + ' minute/s ' +
secondsDifference + ' second/s ');
}
Based on the approved answer:
function(timestamp1, timestamp2) {
var difference = timestamp1 - timestamp2;
var daysDifference = Math.floor(difference/1000/60/60/24);
return daysDifference;
}
A better alternative would be using window.performance API.
const startTime = window.performance.now()
setTimeout(()=>{
const endTime = window.performance.now()
console.log("Time Elapsed : ",endTime-startTime) // logs ~2000 milliseconds
}, 2000)
If your string is Mon May 27 11:46:15 IST 2013, you can convert it to a date object by parsing the bits (assuming 3 letter English names for months, adjust as required):
// Convert string like Mon May 27 11:46:15 IST 2013 to date object
function stringToDate(s) {
s = s.split(/[\s:]+/);
var months = {'jan':0, 'feb':1, 'mar':2, 'apr':3, 'may':4, 'jun':5,
'jul':6, 'aug':7, 'sep':8, 'oct':9, 'nov':10, 'dec':11};
return new Date(s[7], months[s[1].toLowerCase()], s[2], s[3], s[4], s[5]);
}
alert(stringToDate('Mon May 27 11:46:15 IST 2013'));
Note that if you are using date strings in the same timezone, you can ignore the timezone for the sake of difference calculations. If they are in different timezones (including differences in daylight saving time), then you must take account of those differences.
A simple deal to get the time difference.
var initialTime = new Date();
var finalTime = new Date();
console.log({
days: finalTime.getDay() - initialTime.getDay(),
hours: finalTime.getHours() - initialTime.getHours(),
minutes: finalTime.getMinutes() - initialTime.getMinutes(),
seconds: finalTime.getSeconds() - initialTime.getSeconds(),
milliseconds: finalTime.getMilliseconds() - initialTime.getMilliseconds(),
});