Change datetime to number like in jquery - c#

In jquery I do this:
new Date(2009, 12, 1)).getTime()
and I got a huge number like this 1262304000000
How can I change the datetime variable in c# to get the same result that I would get in jquery?

The JavaScript getTime function returns the number of milliseconds since midnight on 1st January 1970.
So to get the same figure from a .NET System.DateTime object, you must subtract the epoch of 1st January 1970 and return the TotalMilliseconds property of the resulting TimeSpan:
var dateOfInterest = new DateTime(2009,12,1);
var epoch = new DateTime(1970,1,1);
var differenceInMilliseconds = (dateOfInterest - epoch).TotalMilliseconds;

C# has DateTime.Ticks Property but this doesn't exactly do with getTime(). Looks like there is no exactly equavalent in C#. You can divide result with 10.000 but still it calculates from 0001 year. Javascripts's getTime() method calculates from 1970.
Gets the number of ticks that represent the date and time of this
instance.
A single tick represents one hundred nanoseconds or one ten-millionth
of a second. There are 10,000 ticks in a millisecond.
The value of this property represents the number of 100-nanosecond
intervals that have elapsed since 12:00:00 midnight, January 1, 0001,
DateTime dt = new DateTime(2009, 12, 1);
dt.Ticks.Dump(); // 633952224000000000
From http://www.w3schools.com/jsref/jsref_gettime.asp
The getTime() method returns the number of milliseconds between
midnight of January 1, 1970 and the specified date.
As a better solution, you can use TimeSpan structure to subtract your dates and use TotalMilliseconds property like;
DateTime start = new DateTime(2009, 12, 1);
DateTime end = new DateTime(1970, 1, 1);
double miliseconds = (start - end).TotalMilliseconds;
miliseconds.Dump(); // 1259625600000

Related

Converting Nanoseconds to Datetime

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 minutes part when i subtract two time values

I want minutes part when i subtract two time values.
I am subtracting current time with 11:30 PM and the result i need in minutes.
I am trying the following code in c#.
TimeSpan eTs = new TimeSpan(23, 30, 00);
int min = System.DateTime.Now.Minute - eTs.Minutes;
but its giving wrong values.
Any help?
Thanks in advance.
It gives wrong value because you are substracting ints. It could even give negative numbers. You should substract the TimeSpan from the DateTime, which gives you another DateTime and use it's Minute property.
var eTs = new TimeSpan(23, 30, 00);
var min = (System.DateTime.Now - eTs).Minute;
EDIT
I am subtracting current time with 11:30 PM and the result i need in
minutes.
No, you are substracting 23 hours and 30 minutes from the current date time.
If you want to know how much minutes have passed since 11:30 PM (what day/month/year), you should:
var min = (System.DateTime.Now - somePastDate).TotalMinutes; //somePastDate must be a DateTime
Do you wanna subtract 2 dateTime and Get the total in minutes try this:
DateTime data = DateTime.Now;
DateTime data2 = DateTime.Now.AddDays(-2);
TimeSpan sub = data - data2;
Console.WriteLine(sub.TotalMinutes);
Or If you wanna subtract minutes from a datetime try this
TimeSpan eTs = new TimeSpan(23, 30, 00);
DateTime data2 = System.DateTime.Now.AddMinutes(-eTs.TotalMinutes);
Console.WriteLine(data2);

ASP.NET: Get milliseconds since 1/1/1970

I have an ASP.NET, VB.NET Date, and I'm trying to get the number of milliseconds since January 1st, 1970. I tried looking for a method in MSDN, but I couldn't find anything. Does anyone know how to do this?
Starting with .NET 4.6, The method ToUnixTimeMilliseconds provides a more accurate solution.
From DateTimeOffset:
DateTimeOffset.Now.ToUnixTimeMilliseconds()
From DateTime:
new DateTimeOffset(dateTime).ToUnixTimeMilliseconds()
Source: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tounixtimemilliseconds?view=netframework-4.6#System_DateTimeOffset_ToUnixTimeMilliseconds
You can subtract any two DateTime instances and get TimeSpan and TotalMilliseconds would give you total milliseconds. Sample below.
DateTime dt1970 = new DateTime(1970, 1, 1);
DateTime current = DateTime.Now;//DateTime.UtcNow for unix timestamp
TimeSpan span = current - dt1970;
Console.WriteLine(span.TotalMilliseconds.ToString());
one liner
//DateTime.MinValue is 01/01/01 00:00 so add 1969 years. to get 1/1/1970
DateTime.Now.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds;
Alternatively, you can use the Ticks property and avoid construction of a temporary object:
long epochTime = (DateTime.UtcNow.Ticks - 621355968000000000) / 10000;
However, this isn't entirely
Reasoning:
DateTime d = new DateTime(1970, 01, 01);
var temp = d.Ticks; // == 621355968000000000
This will provide the UNIX Epoch in milliseconds.
(Respects UTC time instead of your local time)
Split(DateTime.UtcNow.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds(), ".", 2)(0)

Problem finding difference between two time intervals

How can I find difference between two time intervals.
Like 13:45:26.836 - 14:24:18.473 which is of the format "Hour:Min:Sec:Millisecs". Now i need to find the time difference between these two times.
How can i do this in C#.?
Thanks in advance.
Basically, what you need to do is put those time values into DateTime structures. Once you have your two DateTime variables, just subtract them from one another - the result is a variable of type TimeSpan:
DateTime dt1 = new DateTime(2010, 5, 7, 13, 45, 26, 836);
DateTime dt2 = new DateTime(2010, 5, 7, 14, 24, 18, 473);
TimeSpan result = dt2 - dt1;
string result2 = result.ToString();
TimeSpan has a ton of properties that get sets - the difference in all sorts of units, e.g. milliseconds, seconds, minutes etc. You can also just do a .ToString() on it to get a string representation of the result. In result2, you'll get something like this:
00:38:51.6370000
Is that what you're looking for?
i'm posting an example;
you can check it and adapt your program,
/* Read the initial time. */
DateTime startTime = DateTime.Now;
Console.WriteLine(startTime);
/* Do something that takes up some time. For example sleep for 1.7 seconds. */
Thread.Sleep(1700);
/* Read the end time. */
DateTime stopTime = DateTime.Now;
Console.WriteLine(stopTime);
/* Compute the duration between the initial and the end time.
* Print out the number of elapsed hours, minutes, seconds and milliseconds. */
TimeSpan duration = stopTime - startTime;
Console.WriteLine("hours:" + duration.Hours);
Console.WriteLine("minutes:" + duration.Minutes);
Console.WriteLine("seconds:" + duration.Seconds);
Console.WriteLine("milliseconds:" + duration.Milliseconds);
Find the number of seconds; subtract both numbers and then you can figure out the time difference. Depending on the programming language you use, I am positive their must be a library that can handle it.
//Start off with a string
string time1s = "13:45:26.836";
string time2s = "14:24:18.473";
TimeSpan interval = DateTime.Parse(time2s) - DateTime.Parse(time1s);
This will produce a result of:
Days 0 int Hours 0 int
Milliseconds 637 int
Minutes 38 int Seconds 51 int
Ticks 23316370000 long
TotalDays 0.02698653935185185 double
TotalHours 0.64767694444444446 double
TotalMilliseconds 2331637.0 double
TotalMinutes 38.860616666666665 double
TotalSeconds 2331.6369999999997 double

subtract 2 datetime fields to get the days left difference

Would appreciate it if anyone can help me figure out to substract 2 datetime fields to get the days left difference.
This is very easy to do with C#. For comparing DateTimes, we have a class called TimeSpan. The TimeSpan structure, in this case, would be defined as the difference between your two datetimes.
Let's say that your DateTimes are called start and end.
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);
We have established our DateTimes to June 14, 2009 and December 14, 2009.
Now, let's find the difference between the two. To do this, we create a TimeSpan:
TimeSpan difference = end - start;
With this TimeSpan object, you can express the difference in times in many different ways. However, you specifically asked for the difference in days, so here's how you can get that:
Console.WriteLine("Difference in days: " + difference.Days);
Thus, the property is called TimeSpan.Days.
Final Code
//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);
TimeSpan difference = end - start; //create TimeSpan object
Console.WriteLine("Difference in days: " + difference.Days); //Extract days, write to Console.
For more information on using the TimeSpan structure, see this MSDN documentation (especially the C# examples).
Hope I helped!
UPDATE: Some answers have suggested taking doing subtraction in one step, such as with:
int days = (dt2 - dt1).Days;
or
int numDaysDiff = Math.Abs(date2.Subtract(date1).Days);
However, they are the same thing as in my answer, only shortened. This is because the DateTime.Subtract() method and the subtraction operator of DateTimes returns a TimeSpan, from which you can then access the amount of days. I have specifically used the longer approach in my code sample so that you clearly understand what is going on between your DateTime and TimeSpan objects and how it all works. Of course, the other approaches I just mentioned are fine, too.
UPDATE #2:
A very similar question was asked before, and it can be found here. However, the main point of that question was why the code sample (which is essentially equivalent to that of all the answers) sometimes provides an answer which is a day off. I think this is also important to this question.
As the main answer to the other question suggests, you can use this code:
int days = (int)Math.Ceiling(difference.TotalDays);
This code uses Math.Ceiling, which, according to MSDN, is:
Returns the smallest integral value
that is greater than or equal to the
specified double-precision
floating-point number.
How Do You Want to Count the Days?
Thus, we now have an issue with how you want to count the days. Do you want to count part of a day (such as .5 of a day) as:
A full day - this would use Math.Ceiling to round up TimeSpan.TotalDays, so that you're counting started days.
Part of a day - you can just return the TimeSpan.TotalDays (not rounded) as a decimal (in the double datatype)
Nothing - you can ignore that part of a day and just return the TimeSpan.Days.
Here are code samples for the above:
Counting as a full day (using Math.Ceiling() to round up):
//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);
TimeSpan difference = end - start; //create TimeSpan object
int days = (int)Math.Ceiling(difference.TotalDays); //Extract days, counting parts of a day as a full day (rounding up).
Console.WriteLine("Difference in days: " + days); //Write to Console.
Counting as part of a day (NOT using Math.Ceiling(), instead leaving in decimal form as a part of a day):
//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);
TimeSpan difference = end - start; //create TimeSpan object
double days = difference.TotalDays; //Extract days, counting parts of a day as a part of a day (leaving in decimal form).
Console.WriteLine("Difference in days: " + days); //Write to Console.
Counting as nothing of a day (rounding down to the number of full days):
//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);
TimeSpan difference = end - start; //create TimeSpan object
int days = difference.TotalDays; //Extract days, counting parts of a day as nothing (rounding down).
Console.WriteLine("Difference in days: " + days); //Write to Console.
Use
TimeSpan
DateTime departure = new DateTime(2010, 6, 12, 18, 32, 0);
DateTime arrival = new DateTime(2010, 6, 13, 22, 47, 0);
TimeSpan travelTime = arrival - departure;
The easiest way out is, making use of TimeSpan().
This Subtract function will return you the difference between two dates in terms of time span. Now you can fetch fields like days, months etc. To access days you can make use of
Here is the sample code;
VB.Net code;
Dim tsTimeSpan As TimeSpan
Dim ldDate1 as Date
Dim ldDate2 as Date
'Initialize date variables here
tsTimeSpan = ldDate1 .Subtract(ldDate2)
Dim NumberOfDays as integer = tsTimeSpan.days
C#.Net code;
DateTime lDate1;
DateTime lDate2;
TimeSpan tsTimeSpan ;
int NumberOfDays;
//Initialize date variables here
tsTimeSpan = ldDate1 .Subtract(ldDate2);
NumberOfDays = tsTimeSpan.days;
DateTime dt1 = new DateTime(2009,01,01,00,00,00);
DateTime dt2 = new DateTime(2009,12,31,23,59,59);
int days = (dt2 - dt1).Days;
Number of Days Difference
These answers take the number of days as an int from the System.TimeSpan structure that is the result of subtracting two System.DateTime fields...
Quick answer - gets the number of days difference.
int numDaysDiff = date2.Subtract(date1).Days;
Alternate answer - uses Math.Abs to ensure it's not a negative number, just in case the dates might be supplied in either order.
int numDaysDiff = Math.Abs( date2.Subtract(date1).Days );
Some sample data to finish it off using System namespace:
// sample data
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddDays(10);
MSDN References (and more sample code ):
System.TimeSpan structure
System.DateTime structure
System.Math.Abs(..) method
DateTime theDate = DateTime.Today;
int datediff = theDate.Subtract(expiryDate).Negate().Days;
if expiryDate > theDate then you get Negative value: -14
expiryDate is less than theDate then you get positive value: 14
You May obviously want this in a scenario such as
Send a Notification Email 14days before expiry
Send another notification Email 14 days after expiry
You need a difference that could be negative value
You should look at TimeSpan.
To get the exact days ignoring the time section
DateTime d1 = Convert.ToDateTime(DateTime.Now.ToShortDateString());
DateTime d2 = Convert.ToDateTime(DateTime.Now.AddDays(46).ToShortDateString());
var days = Convert.ToInt32(d2.Subtract(d1).TotalDays)

Categories

Resources