I'm using momentJS to find the difference between two times and format to hh:mm:ss. Ver: "moment": "~2.10.6"
The problem I'm having is an extraneous 7 hours being added to a time whose difference is only 1 minute, 1 second.
var diff_ms = moment('2016-07-29 10:35:18').diff('2016-07-29 10:34:17');
61000
var diff = moment(diff_ms).format('hh mm ss')
"07 01 01"
Convert milliseconds to hours and minutes using Momentjs says to specify the time unit as milliseconds, moment.duration(x, 'milliseconds');, but since it's returning the correct minutes and seconds (01 01), it seems it's correctly defaulting to milliseconds.
I can do this the "un-momentJS" way:
var a = moment.duration(61000, 'milliseconds');
a: n {_milliseconds: 61000, _days: 0, _months: 0, _data: Object,
_locale: l}
var b = a.hours() + ':' + a.minutes() + ':' + a.seconds();
b: 0:1:1
But don't have an easy way of formatting this output to hh:mm:ss using string concatenation like this.
Related
I need to sum the hours and minutes so I am doing this like ill convert hours in second and minutes in second then sum it
var totalServiceSeconds = minsSeconds + hoursSeconds;
var c = Duration(seconds: totalServiceSeconds);
print('c ${c.toString()}');
it's showing c 25:05:00.000000 which is correct
Know I need to show this as hours and minutes in the text widget. So I am converting to DateTime like this
var format = DateFormat("HH:mm");
DateTime totalServiceTime = format.parse(c.toString());
But it's printing it like this totalServiceTime 1970-01-02 01:05:00.000
This issue is only when the hours are 24 or more. If my hours are 24 then it's showing 0 and if greater than 24 then it's showing 1 2 so on. I know it because it's considering 24 as 0 but what can I do about this?
I want to show 24 if it's 24 hours or if greater than 24 like 26 need to show 26.
You do not want to convert it into a DateFormat because time steps of 24 hours is how they count a full day. Instead you should format var c as shown below
var totalServiceSeconds = minsSeconds + hoursSeconds;
var c = Duration(seconds: totalServiceSeconds);
print('c ${c.toString()}');
String FormatDuration = "${c.inHours}:${c.inMinutes.remainder(60)}:${(c.inSeconds.remainder(60))}";
print(FormatDuration);
String FormatDuration2 = "${c.inHours} hours ${c.inMinutes.remainder(60)} minutes ${(c.inSeconds.remainder(60))} seconds";
print(FormatDuration2);
The output will then be
c 25:05:00.000000 <-------previous
25:5:0 <-------new option 1
25 hours 5 minutes 0 seconds <-------new option 2
Sorry if similar questions have been asked too many times, but it seems that there's one or more issues with every answer I find.
I have a date in the form of a String: Ex.: "04112005"
This is a date. 4th of November, 2005.
I want to get the difference, in years and days, between the current date and this date.
The code I have so far gets the year and just substracts them:
fun getAlderFraFodselsdato(bDate: String): String {
val bYr: Int = getBirthYearFromBirthDate(bDate)
var cYr: Int = Integer.parseInt(SimpleDateFormat("yyyy").format(Date()))
return (cYr-bYr).toString()
}
However, naturally, this is quite innacurate, since the month and days aren't included.
I've tried several approaches to create Date, LocalDate, SimpleDate etc. objects and using these to calcualate the difference. But for some reason I haven't gotten any of them to work.
I need to create a Date (or similar) object of the current year, month and day. Then I need to create the same object from a string containing say, month and year (""04112005""). Then I need to get the difference between these, in years, months and days.
All hints are appreciated.
I would use java.time.LocalDate for parsing and today along with a java.time.Period that calculates the period between two LocalDates for you.
See this example:
fun main(args: Array<String>) {
// parse the date with a suitable formatter
val from = LocalDate.parse("04112005", DateTimeFormatter.ofPattern("ddMMyyyy"))
// get today's date
val today = LocalDate.now()
// calculate the period between those two
var period = Period.between(from, today)
// and print it in a human-readable way
println("The difference between " + from.format(DateTimeFormatter.ISO_LOCAL_DATE)
+ " and " + today.format(DateTimeFormatter.ISO_LOCAL_DATE) + " is "
+ period.getYears() + " years, " + period.getMonths() + " months and "
+ period.getDays() + " days")
}
The output for a today of 2020-02-21 is
The difference between 2005-11-04 and 2020-02-21 is 14 years, 3 months and 17 days
It Works Below 26 API level
There are too many formates of dates you just enter the format of date and required start date and end date. It will show you result. You just see different date formate hare and here if you need.
tvDifferenceDateResult.text = getDateDifference(
"12 November, 2008",
"31 August, 2021",
"dd MMMM, yyyy")
General method to calculate date difference
fun getDateDifference(fromDate: String, toDate: String, formater: String):String{
val fmt: DateTimeFormatter = DateTimeFormat.forPattern(formater)
val mDate1: DateTime = fmt.parseDateTime(fromDate)
val mDate2: DateTime = fmt.parseDateTime(toDate)
val period = Period(mDate1, mDate2)
// period give us Year, Month, Week and Days
// days are between 0 to 6
// if you want to calculate days not weeks
//you just add 1 and multiply weeks by 7
val mDays:Int = period.days + (period.weeks*7) + 1
return "Year: ${period.years}\nMonth: ${period.months}\nDay: $mDays"
}
For legacy Date functions below api 26 without running desugaring with Gradle plugin 4.0, java.time.* use:
fun getLegacyDateDifference(fromDate: String, toDate: String, formatter: String= "yyyy-MM-dd HH:mm:ss" , locale: Locale = Locale.getDefault()): Map<String, Long> {
val fmt = SimpleDateFormat(formatter, locale)
val bgn = fmt.parse(fromDate)
val end = fmt.parse(toDate)
val milliseconds = end.time - bgn.time
val days = milliseconds / 1000 / 3600 / 24
val hours = milliseconds / 1000 / 3600
val minutes = milliseconds / 1000 / 3600
val seconds = milliseconds / 1000
val weeks = days.div(7)
return mapOf("days" to days, "hours" to hours, "minutes" to minutes, "seconds" to seconds, "weeks" to weeks)
}
The above answers using java.time.* api is much cleaner and accurate though.
I have two dates in EPOCH value.
Open : 1579269496000
Close : 1579270005225
I want to get display different between two dates.
So difference = Close - Open = <ddd> Days <hh> Hours <mm> Mins <ss> Sec.
I'm using Moment.js to convert the date but I don't see to substract EPOCH date using that.
var c = new Date(close);
var o = new Date(open);
var seconds =enter code here (c.getTime() - o.getTime()) / 1000;
var ms = moment(close,"DD/MM/YYYY HH:mm:ss").diff(moment(open,"DD/MM/YYYY HH:mm:ss"));
Hope this solves your concern.
First convert epoch value to the value supported by momentJS. Then you could get the difference in years and add that to the initial date; then get the difference in weeks and add that to the initial date again.
var moment = require("moment");
var a = "1582113418";
var b = "1582113444";
var aa = moment.unix(a); // converted value
var bb = moment.unix(b); // converted value
var days = bb.diff(aa, "days");
aa.add(days, "years");
var hours = bb.diff(aa, "hour");
aa.add(hours, "hours");
var seconds = bb.diff(aa, "seconds");
console.log(days + " days " + hours + " hours " + seconds + " seconds");
Working sandbox: https://codesandbox.io/s/adoring-shamir-0yuxq
I took this piece from an unencrypted .DAT file:
Code:
00 e1 27 17 6f e6 69 c0
Which translates to 63,374,851,375,000,000 in decimal. The units for the number are microseconds.
And this huge number cannot bypass the 1st January 1970 00:00:00 format; such a format that most converters use today.
So, yes. Is there such a converter that uses the 1st January of the year 1 format? Or how shall I make one?
And by the way, a timestamp is both date and time.
Thanks in advance!
You do not say what language are you using, if it is a .NET language, you can use: http://msdn.microsoft.com/en-us/library/z2xf7zzk.aspx for that constructor the input is in nanoseconds (are you sure that your number is in milliseconds and not in nanoseconds?).
If you are sure it is in milliseconds, the conversion to nanoseconds should be easy: 1 millisecond = 1 000 000 nanoseconds.
But I have the feeling that those are nanoseconds and not milliseconds...
Now that you have told us that it is in microseconds:
C# Example from decimal to yyyy dd MM hh:mm:ss
long microseconds = 63370738175000000;
long ticks = microseconds * 10;
DateTime timestamp = new DateTime(ticks);
Console.WriteLine(timestamp.ToString("yyyy dd MM hh:mm:ss"));
It prints:
2009 20 02 02:49:35
The other way around from yyyy dd MM hh:mm:ss to decimal
String dateString = "2009 20 02 02:49:35";
DateTime timestamp = DateTime.ParseExact(dateString, "yyyy dd MM hh:mm:ss",CultureInfo.CurrentCulture);
long ticks = timestamp.Ticks;
long microseconds = ticks / 10;
Console.WriteLine(microseconds);
It prints:
63370694975000000
And if you want it in hexadecimal just write:
Console.WriteLine(microseconds.ToString("X"));
Then it will print:
E1234FB3278DC0
If you want the answer in another programming language, please add that to you question.
In JAVA in order to convert microseconds into java.sql.Timestamp:
public static Timestamp getTimestampFromMicros(long pMicros) {
long millis = TimeUnit.MICROSECONDS.toMillis(pMicros);
long shaaritInMicros = pMicros - TimeUnit.MILLISECONDS.toMicros(millis);
Timestamp ts = new Timestamp(millis);
long nanos = ts.getNanos() + TimeUnit.MICROSECONDS.toNanos(shaaritInMicros);
ts.setNanos((int)nanos);
return ts;
}
Use below Java code to covert microseconds to date and time,
long msec = microseconds * 1/1000;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormat.format(msec);
Which will returns,
2016-01-27 03:41:12
I been working on parsing out bookmarks from an export file generated by google bookmarks. This file contains the following date attributes:
ADD_DATE="1231721701079000"
ADD_DATE="1227217588219000"
These are not standard unix style timestamps. Can someone point me in the right direction here? I'll be parsing them using c# if you are feeling like really helping me out.
Chrome uses a modified form of the Windows Time format (“Windows epoch”) for its timestamps, both in the Bookmarks file and the history files. The Windows Time format is the number of 100ns-es since January 1, 1601. The Chrome format is the number of microseconds since the same date, and thus 1/10 as large.
To convert a Chrome timestamp to and from the Unix epoch, you must convert to seconds and compensate for the difference between the two base date-times (11644473600).
Here’s the conversion formulas for Unix, JavaScript (Unix in milliseconds), Windows, and Chrome timestamps (you can rearrange the +/× and -/÷, but you’ll lose a little precision):
u : Unix timestamp eg: 1378615325
j : JavaScript timestamp eg: 1378615325177
c : Chrome timestamp eg: 13902597987770000
w : Windows timestamp eg: 139025979877700000
u = (j / 1000)
u = (c - 116444736000000) / 10000000
u = (w - 1164447360000000) / 100000000
j = (u * 1000)
j = (c - 116444736000000) / 10000
j = (w - 1164447360000000) / 100000
c = (u * 10000000) + 116444736000000
c = (j * 10000) + 116444736000000
c = (w / 10)
w = (u * 100000000) + 1164447360000000
w = (j * 100000) + 1164447360000000
w = (c * 10)
Note that these are pretty big numbers, so you’ll need to use 64-bit numbers or else handle them as strings like with PHP’s BC-math module.
In Javascript the code will look like this
function chromeDtToDate(st_dt) {
var microseconds = parseInt(st_dt, 10);
var millis = microseconds / 1000;
var past = new Date(1601, 0, 1).getTime();
return new Date(past + millis);
}
1231721701079000 looks suspiciously like time since Jan 1st, 1970 in microseconds.
perl -wle 'print scalar gmtime(1231721701079000/1_000_000)'
Mon Jan 12 00:55:01 2009
I'd make some bookmarks at known times and try it out to confirm.
Eureka! I remembered having read the ADD_DATE’s meaning at some website, but until today, I could not find it again.
http://MSDN.Microsoft.com/en-us/library/aa753582(v=vs.85).aspx
offers this explanation as a “Note” just before the heading “Exports and Imports”:
“Throughout this file[-]format definition, {date} is a decimal integer that represents the number of seconds elapsed since midnight January 1, 1970.”
Before that, examples of {date} were shown:
<DT><H3 FOLDED ADD_DATE="{date}">{title}</H3>
…
and
<DT>{title}
…
Someday, I will write a VBA macro to convert these to recognizable dates, but not today!
If someone else writes a conversion script first, please share it. Thanks.
As of the newest Chrome Version 73.0.3683.86 (Official Build) (64-bit):
When I export bookmark, I got an html file like "bookmarks_3_22_19.html".
And each item has an 'add_date' field which contains date string. like this:
Stack Overflow
This timestamp is actually seconds (not microseconds) since Jan 1st, 1970. So we can parse it with Javascript like following code:
function ChromeTimeToDate(timestamp) {
var seconds = parseInt(timestamp, 10);
var dt = new Date();
dt.setTime(seconds * 1000);
return dt;
}
For the upper example link, we can call ChromeTimeToDate('1553220774') to get Date.
ChromeTimeToDate('1553220774')
12:09:03.263 Fri Mar 22 2019 10:12:54 GMT+0800 (Australian Western Standard Time)
Initially looking at it, it almost looks like if you chopped off the last 6 digits you'd get a reasonable Unix Date using the online converter
1231721701 = Mon, 12 Jan 2009 00:55:01 GMT
1227217588 = Thu, 20 Nov 2008 21:46:28 GMT
The extra 6 digits could be formatting related or some kind of extended attributes.
There is some sample code for the conversion of Unix Timestamps if that is in fact what it is.
look here for code samples: http://www.epochconverter.com/#code
// my groovy (java) code finally came out as:
def convertDate(def epoch)
{
long dv = epoch / 1000; // divide by 1,000 to avoid milliseconds
String dt = new java.text.SimpleDateFormat("dd/MMM/yyyy HH:mm:ss").format(new java.util.Date (dv));
// to get epoch date:
//long epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() * 1000;
return dt;
} // end of def
So firefox bookmark date exported as json gave me:
json.lastModified :1366313580447014
convert from epoch date:18/Apr/2013 21:33:00
from :
println "convert from epoch date:"+convertDate(json.lastModified)
function ConvertToDateTime(srcChromeBookmarkDate) {
//Hp --> The base date which google chrome considers while adding bookmarks
var baseDate = new Date(1601, 0, 1);
//Hp --> Total number of seconds in a day.
var totalSecondsPerDay = 86400;
//Hp --> Read total number of days and seconds from source chrome bookmark date.
var quotient = Math.floor(srcChromeBookmarkDate / 1000000);
var totalNoOfDays = Math.floor(quotient / totalSecondsPerDay);
var totalNoOfSeconds = quotient % totalSecondsPerDay;
//Hp --> Add total number of days to base google chrome date.
var targetDate = new Date(baseDate.setDate(baseDate.getDate() + totalNoOfDays));
//Hp --> Add total number of seconds to target date.
return new Date(targetDate.setSeconds(targetDate.getSeconds() + totalNoOfSeconds));
}
var myDate = ConvertToDateTime(13236951113528894);
var alert(myDate);
//Thu Jun 18 2020 10:51:53 GMT+0100 (Irish Standard Time)
#Python program
import time
d = 1630352263 #for example put here, if (ADD_DATE="1630352263")
print(time.ctime(d)) #Mon Aug 30 22:37:43 2021 - you will see