I have class that open Pcap fileand have this 2 members: Seconds and Microseconds (both int).
How can i create from this 2 fields DateTime ?
This is what i have try:
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, packet.Seconds);
And got this error:
Hour, Minute, and Second parameters describe an un-representable
DateTime.
Code:
var dateTime = new DateTime(1970, 1, 1).AddSeconds(packet.Seconds).AddTicks(packet.Microseconds * 10);
The problem is that the seconds parameter in that constructor must be between 0 and 59 inclusively. What you really want is 1970-1-1 plus the number of seconds.
var dateTime = new DateTime(1970, 1, 1).AddSeconds(packet.Seconds).AddSeconds(packet.Microseconds / 1000000.0);
Related
I'm having a hard time understanding why this is happening or even if this should be happening. If I calculate the TimeSpan between two DateTime objects (same date, different times) and compare it to the same calculation using two TimeOnly objects I get different results.
var start = new DateTime(1, 1, 1, 14, 0, 0);
var end = new DateTime(1, 1, 1, 10, 0, 0);
Console.WriteLine(end - start); // Prints -4 hours
However...
var start = new TimeOnly(14, 0, 0);
var end = new TimeOnly(10, 0, 0);
Console.WriteLine(end - start); // Prints 20 hours???
Isn't the span between starting at 2pm and ending at 10am always a span of -4 hours? Interestingly enough if I take the second one and do Console.WriteLine(end.ToTimeSpan() - start.ToTimeSpan()); I end up with -4 hours.
This feels like an error on TimeOnly's part but I don't know. Here is a fiddle I did comparing results between NodaTime, System.DateTime, converting System.TimeOnly to TimeSpan, and System.TimeOnly.
I'm having a little trouble converting nanoseconds to DateTime so i can use the Google Fit API (https://developers.google.com/fit/rest/v1/reference/users/dataSources/datasets/get)
Dataset identifier that is a composite of the minimum data point start
time and maximum data point end time represented as nanoseconds from
the epoch. The ID is formatted like: "startTime-endTime" where
startTime and endTime are 64 bit integers.
I was able to convert from datetime to Nanoseconds this way
DateTime zuluTime = ssDatetime.ToUniversalTime();
DateTime unixEpoch = new DateTime(1970, 1, 1);
ssNanoSeconds = (Int32)(zuluTime.Subtract(unixEpoch)).TotalSeconds + "000000000";
But now i need to convert nanoseconds to DateTime. How can i do it?
Use AddTicks method. Don't forget to divide nanoseconds by 100 to get ticks.
long nanoseconds = 1449491983090000000;
DateTime epochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime result = epochTime.AddTicks(nanoseconds / 100);
Ticks property represents 100 nanoseconds. So how about :
var ssNanoSeconds = ((zuluTime.Subtract(unixEpoch)).Ticks / 100)
From nanoseconds to DateTime
DateTime dateTime = new DateTime(1970, 1, 1).AddTicks(nanoSeconds * 100) ;
To convert nanoseconds to a DateTime object, you can do the following:
Divide the nanoseconds value by 1,000,000,000 to get the equivalent number of seconds.
Create a DateTime object representing the Unix epoch (January 1, 1970).
Add the number of seconds to the Unix epoch to get the desired DateTime object.
long nanoseconds = 1234567890123; // nanoseconds value to convert
// Divide the nanoseconds value by 1,000,000,000 to get the equivalent number of seconds
int seconds = (int)(nanoseconds / 1000000000);
// Create a DateTime object representing the Unix epoch (January 1, 1970)
DateTime unixEpoch = new DateTime(1970, 1, 1);
// Add the number of seconds to the Unix epoch to get the desired DateTime object
DateTime datetime = unixEpoch.AddSeconds(seconds);
Note that this will only work correctly if the nanoseconds value is within the range of values that can be represented by a DateTime object (approximately 292 million years before or after the Unix epoch). If the nanoseconds value is outside of this range, the resulting DateTime object will not be accurate.
How do I get the time difference between two DateTime objects using C#?
The following example demonstrates how to do this:
DateTime a = new DateTime(2010, 05, 12, 13, 15, 00);
DateTime b = new DateTime(2010, 05, 12, 13, 45, 00);
Console.WriteLine(b.Subtract(a).TotalMinutes);
When executed this prints "30" since there is a 30 minute difference between the date/times.
The result of DateTime.Subtract(DateTime x) is a TimeSpan Object which gives other useful properties.
You want the TimeSpan struct:
TimeSpan diff = dateTime1 - dateTime2;
A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date.
There are various methods for getting the days, hours, minutes, seconds and milliseconds back from this structure.
If you are just interested in the difference then:
TimeSpan diff = (dateTime1 - dateTime2)).Duration();
will give you the positive difference between the times regardless of the order.
If you have just got the time component but the times could be split by midnight then you need to add 24 hours to the span to get the actual difference:
TimeSpan diff = dateTime1 - dateTime2;
if (diff < 0)
{
diff = diff + TimeSpan.FromDays(1);
}
What you need is to use the DateTime classs Subtract method, which returns a TimeSpan.
var dateOne = DateTime.Now;
var dateTwo = DateTime.Now.AddMinutes(-5);
var diff = dateTwo.Subtract(dateOne);
var res = String.Format("{0}:{1}:{2}", diff.Hours,diff.Minutes,diff.Seconds));
The way I usually do it is subtracting the two DateTime and this gets me a TimeSpan that will tell me the diff.
Here's an example:
DateTime start = DateTime.Now;
// Do some work
TimeSpan timeDiff = DateTime.Now - start;
timeDiff.TotalMilliseconds;
IF they are both UTC date-time values you can do TimeSpan diff = dateTime1 - dateTime2;
Otherwise your chance of getting the correct answer in every single possible case is zero.
var startDate = new DateTime(2007, 3, 24);
var endDate = new DateTime(2009, 6, 26);
var dateDiff = endDate.Subtract(startDate);
var date = string.Format("{0} years {1} months {2} days", (int)dateDiff.TotalDays / 365,
(int)(dateDiff.TotalDays % 365) / 30, (int)(dateDiff.TotalDays % 365) / 30);
Console.WriteLine(date);
private void button1_Click(object sender, EventArgs e)
{
TimeSpan timespan;
timespan = dateTimePicker2.Value - dateTimePicker1.Value;
int timeDifference = timespan.Days;
MessageBox.Show(timeDifference.ToString());
}
You can use in following manner to achieve difference between two Datetime Object. Suppose there are DateTime objects dt1 and dt2 then the code.
TimeSpan diff = dt2.Subtract(dt1);
You need to use a TimeSpan. Here is some sample code:
TimeSpan sincelast = TimeSpan.FromTicks(DateTime.Now.Ticks - LastUpdate.Ticks);
I am having some trouble converting a date found in the file that stores browser history to a normal DateTime.
The file is located at: C:\Users[username]\AppData\Roaming\Mozilla\Firefox\Profiles[profilename]\places.sqlite
The table in question is: [moz_places]
The column is: [last_visit_date]
I've tried using the unix epoch and webkit format(like chrome uses), but neither are giving me the results I expect.
Here is my Unix conversion(not working):
public static DateTime FromUnixTime(long unixTime)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddSeconds(unixTime);
}
This is my webkit conversion code: (Also not working for these dates, it works with chromes webkit dates)
public static DateTime ConvertWebkitTimeToDateTime(long ticks)
{
//Set up a date at the traditional starting point for unix time.
DateTime normalDate = new DateTime(1970, 1, 1, 0, 0, 0, 0);
//Subtract the amount of seconds from 1601 to 1970.
long convertedTime = (ticks - 11644473600000000);
//Devide by 1000000 to convert the remaining time to seconds.
convertedTime = convertedTime / 1000000;
//Add the seconds we calculated above.
normalDate = normalDate.AddSeconds(convertedTime);
//Finally we have the date.
return normalDate;
}
So what's the deal with these dates Firefox is storing? Here are a couple sample dates that should all be around today's date or yesterday's.(about 10/17/2013)
1373306583389000
1373306587125000
1373306700392000
Any help or documentation links would be awesome, thanks.
Unix timestamps are measured in seconds.
These values are larger by a factor of one million, i.e., they are using microseconds:
> select datetime(1373306583389000 / 1000000, 'unixepoch');
2013-07-08 18:03:03
Solution in C#:
public static DateTime FromUnixTime(long unixTime)
{
unixTime = unixTime / 1000000;
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddSeconds(unixTime);
}
CL. was correct in that this is simply the millisecond value from the Unix epoch.
Solution in SQL:
Here is a resource that explains his solution in greater detail:
https://support.mozilla.org/en-US/questions/835204
I'm having problems when I'm trying to substract hr2 with hr1 in a specific situation, for example, when hr1 = 13:00 and hr2 = 15:00, ok, the result is 02:00.
But when the values are: hr1 = 22:00 and hr2 = 02:00, the result is 20:00.
The result should be 04:00.
TimeSpan ts1 = hr1.Subtract(hr2).Duration();
TextBox1.Text = ts1.ToString();
How can I solve this problem?
I understand what you want, but how you currently try to achieve it makes no sense. 22 hours minus 20 hours is 2 hours, which is correct.
You probably want this:
new DateTime(1, 1, 2, 2, 0, 0) - new DateTime(1, 1, 1, 22, 0, 0)
You don't want to subtract TimeSpan's, you want to subtract dates (fake dates in this case).
Invoking Duration() will always result in a positive TimeSpan. The problem is coming from the fact that you are discarding days in your calculation. 22:00-02:00 is 20:00. I believe you are expecting it to be 04:00 because 02:00 represents "tomorrow." If that is what you want, you will need to calculate 22:00-(02:00+24:00) which will give you -04:00, which will become 04:00 when you invoke Duration().
You are trying to subtract two "spans", or durations, of time--not fixed points in time. What your code is currently saying is, I want to subtract two hours from twenty hours (which is indeed twenty hours). Instead, you need to use DateTimes. The hard part is going to be deciding the date for your timespans. I would rework the code to use DateTimes and preserve the "moments" in time that you are actually attempting to calculate.
Edit: Converting from a TimeSpan to a DateTime can cause you to lose information that affects the outcome of the result:
var ts1 = new DateTime (1, 1, 1, hr1.Hours, hr1.Minutes, hr1.Seconds, hr1.Milliseconds) -
new DateTime (1, 1, 1, hr2.Hours, hr2.Minutes, hr2.Seconds, hr2.Milliseconds);
is different than:
var ts1 = new DateTime (1, 1, 1, hr1.Hours, hr1.Minutes, hr1.Seconds, hr1.Milliseconds) -
new DateTime (1, 1, 2, hr2.Hours, hr2.Minutes, hr2.Seconds, hr2.Milliseconds);
or:
var ts1 = new DateTime (1, 1, 2, hr1.Hours, hr1.Minutes, hr1.Seconds, hr1.Milliseconds) -
new DateTime (1, 1, 1, hr2.Hours, hr2.Minutes, hr2.Seconds, hr2.Milliseconds);
Which is why you need to maintain the "point in time" with a DateTime.