Converting TimeSpan Hours to DateTime - c#

Commented Code As Posted by Arif Eqbal the below Converts a TimeSpan to a DateTime
A problem with the above is that the conversion returns the incorrect number of days as specified in the TimeSpan. Using the above, the below returns 3 and not 2 as specified. The minutes and seconds are preserved. ~~ Ideas on how to preserve the 2 days in the TimeSpan arguments and return them as the DateTime day?
A second problem of this conversion is that if I want to add the hours in days to the hours in the TimeSpan and return them as DateTime hours, e.g. Format = "hh:mm" or 49:30, there is no way to add the hours together in a DateTime object. Essentially I want to convert TimeSpan.TotalHours to the Hours component of the DateTime object. I understand this likely requires a string conversion, but there doesn't seem to be an elegant solution in .Net 3.5. Unfortunately I do not have the luxury of the converters from 4.0 or 4.5.
public void test()
{
// Arif Eqbal
//DateTime dt = new DateTime(2012, 01, 01);
//TimeSpan ts = new TimeSpan(1, 0, 0, 0, 0);
//dt = dt + ts;
_ts = new TimeSpan(2, 1, 30, 10);`
var format = "dd";
var returnedVal = _ts.ToString(format);
Assert.That(returnedVal, Is.EqualTo("2")); //returns 3 not 2
}
Thanks - Glenn

It returns "02" when I try it.
The "dd" format makes it put leading zeroes if necessary, but you have failed to account for this in your Is.EqualTo("2")
Therefore your assertion fails (but you mistakenly thought that it was returning 3).
I tested this by copy/pasting your code into a Console app:
var _ts = new TimeSpan(2, 1, 30, 10);
var format = "dd";
var returnedVal = _ts.ToString(format);
Console.WriteLine(returnedVal); // Prints "02"
[EDIT] Aha! Now I know what you've done. Your code is actually like this:
var _ts = new TimeSpan(2, 1, 30, 10);
var format = "dd";
DateTime formatDateTime = new DateTime(2012, 01, 01);
var conversionResult = formatDateTime + _ts;
string result = conversionResult.ToString(format);
But note what the type of conversionResult is DateTime, not TimeSpan.
So you're doing here is using the format "dd" with a DateTime object, and "dd" for a DateTime means "The day of the month".
So you took the date 2012-01-01 and added 2 days (and a bit) to it to make it 2012-01-03, and then you made a string out of the day of the month part, which of course is 3.
Problem explained!

Related

How can I convert the number of seconds since Jan 1st 1970 into a datetime value?

I have a number that is the number of seconds since January 1st 1970. It was created with this:
var utcNow = (int) Math.Truncate(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
Now need to convert that number to a date in string form like this:
Tue, Jan 15, 2019
Can someone give me some suggestions on how I can do this. I think I can format it myself but I need a suggestion on how to convert the integer utcNow into a datetime first.
static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
...
DateTime time = epoch.AddSeconds(utcNow);
You can also use this in reverse:
var seconds = (time - epoch).TotalSeconds;
(which gives a double, but you can cast it to int or long etc)
Some answer are already given, and work. But this is, I believe, the most elegant way of doing it. I'm using DateTimeOffset.FromUnixTimeSeconds(int64)
DateTimeOffset dt = DateTimeOffset.FromUnixTimeSeconds(utcNow);
And now you can convert it into a DateTime Struct with help of this blog entry
Substract the given time from current time and it gives timespan instance, from that you can get total seconds
var fromDate = new DateTime(1970,1 ,1);
var diffrance = DateTime.UtcNow.Subtract(fromDate);
Console.WriteLine(diffrance.TotalSeconds);

C# date format over 1 day

I'm trying to format a date from now, to few seconds, hours, maybe days, similar as Clash of Clans working timers Like this :
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
dateTime = dateTime.AddSeconds(80000);
return dateTime.ToString("H'h' mm'min'");
It works great actually, I get '22h 13min', only for minutes and hours. If I try to print days with it, like this :
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
dateTime = dateTime.AddSeconds(80000);
return dateTime.ToString("d'd' H'h' mm'min'");
I'll have '1d 22h 13min' returned. So for example if I try to convert 1 day to second (86400sec), this code will return 2 days, instead of 1 day.
How can I solve this problem properly without tricks like hard substract by 1 the day returned ?
EDIT1:
For example, expected result for one day is :
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
dateTime = dateTime.AddSeconds(86400);
return dateTime.ToString("d'j' H'h' mm'min'");
return 2d 0h 00min, instead of 1d 0h 00min.
For DateTime, day is the day of the month. What you want is a TimeSpan.
var span = TimeSpan.FromSeconds(80000);
Console.WriteLine(span.ToString(#"d'd 'h'h 'm'min'"));
outputs
0d 22h 13min
Your code dateTime = dateTime.AddSeconds(80000); will assign the value 1/1/1970 10:13:20 to the dateTime variable, hence you are getting the output as 1d 22h 13min by dateTime.ToString("d'd' H'h' mm'min'");. So if you want to get the next day you can use dateTime = dateTime.AddDays(1); or add it as seconds as you did. ie., dateTime = dateTime.AddSeconds(86400);
The "d" format specifier returns the day number of month. Since you add 1 day to 1st January, it will be 2nd January and that's why this specifier returns 2.
If I understand clearly, you might wanna use TimeSpan instead.
TimeSpan ts = TimeSpan.FromSeconds(86400);
ts.ToString("d'd 'h'h 'mm'min'"); // 1d 0h 00min
or
TimeSpan ts = TimeSpan.FromSeconds(80000);
ts.ToString("d'd 'h'h 'mm'min'"); // 0d 22h 13min
Then you can format this value.
Or you can use DateTime.AddDays method to subctact 1 day like
dateTime = dateTime.AddDays(-1);
for your dateTime if you really wanna use DateTime.

long value to date c#

My server is sending me the following value 13928550480000 which I know represents the date 02/19/2014. But I am not able to figure out how to get to the date from the long value.
I tried various ways of converting long to date using c# date time class but not able to get to the correct date i.e. 02/19/2014
long dateL = 13928550480000;
DateTime dt = new DateTime(dateL);
var dtstr = dt.ToString("MM/dd/yyyy");
var onlyDate = dt.Date;
DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime date = start.AddMilliseconds(dateL).ToLocalTime();
var dtstr1 = date.ToString("MM/dd/yyyy");
It looks like your source number represents number of 0.10 ms increments since 1-1-1970 (either that or a typo):
long dateL = 13928550480000;
DateTime start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime date = start.AddMilliseconds(dateL/10).ToLocalTime();
// ***
// ^------
var dtstr1 = date.ToString("MM/dd/yyyy"); // 02/19/2014
I suspect the time zone difference is irrelevant to your problem.
Did you write too many zeros at the end of your big number? That is, does it really end in 0000 and not just 000?
If it really is 0000, then it appears to be measuring time in 100-microsecond increments (10,000 time increments per second). But it is probably also giving you time in GMT and you are expecting to derive local time from it. The time 1392855048 seconds from Jan. 1, 1970 would be 10 minutes 48 seconds past midnight on Feb. 20, 2014. Depending on your time zone, that could be sometime on Feb. 19 local time.

Trivia: How to convert a JSON2.org DateTime string to C# DateTime

Asp.Net MVC 2 Futures doesn't seem to handle JSON DateTime well (including double and decimal values). As such, I setup all inputs as string, used Data Validation, and things worked pretty well.
However, I have this JSON2.js date from Firefox 3.6:
"/Date(1288296203190)/"
How do I turn this in to a valid date in C#?
var a = new DateTime(1288296203190);
That doesn't give the right date (1/2/0001 11:47:09 AM) instead of Thu Oct 28 2010 16:03:23 GMT-0400 (Eastern Daylight Time). It's probably because a 32 bit integer is only 10 digits. However, this fails too:
var a = Int64.Parse("1288296203190");
var b = new DateTime(a);
b's value is 1/2/0001 11:47:09 AM.
What did it do? Wrap? Is this some kind of time travel "signed bit" issue?
The issue is the difference in epoch. Looks like the JSON2.js date you have uses the unix epoch (January 1, 1970) measured in ms. From the System.DateTime(long ticks) documenttion:
expects A date and time expressed in the number of 100-nanosecond intervals that have elapsed since January 1, 0001 at 00:00:00.000 in the Gregorian calendar.
Something like this should get you what you want.
var unixEpoch = DateTime(1970, 1, 1);
var ticksSinceEpoch = 1288296203190 * 10000;
var time = new DateTime(unixEpoch.Ticks + ticksSinceEpoch);
And there is even better way (which also takes your local timezone into account):
Just create this integer number extension -
public static class currency_helpers {
public static DateTime UNIXTimeToDateTime(this int unix_time) {
return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(unix_time).ToLocalTime();
}
}
And then call it wherever like this:
var unix_time = 1336489253;
var date_time = unix_time.UNIXTimeToDateTime();
The value of date_time is:
5/8/2012 10:00:53 AM
(via: http://www.codeproject.com/Articles/10081/UNIX-timestamp-to-System-DateTime?msg=2494329#xx2494329xx)
var jsonDate = "/Date(1288296203190+0530)/";
var strSec = jsonDate.Substring(6, 13);
var strTimeZone = jsonDate.Substring(19, 5);
sec = double.Parse(strSec);
var timeZoneHr = double.Parse(strTimeZone);
var timeZoneMin = timeZoneHr % 100;
timeZoneHr = Math.Ceiling(timeZoneHr / 100);
var date = new System.DateTime(1970, 1, 1, 0, 0, 0, 0)
.AddMilliseconds(sec)
.AddHours(timeZoneHr)
.AddMinutes(timeZoneMin);
I parsed the string myself. Its working fine for me. Anybody have other optimized way, please let me know.
This question is basically the same as this one: ASP.net c# Parse int as datetime.
And I think the accepted answer there is better than #matheeeny's answer (although matheeeny explained well the problem of OP's original solution).
I'll copy here LukeH's accepted answer:
var dt = new DateTime(1970, 1, 1).AddMilliseconds(1286294501433);
You might also need to specify the DateTimeKind explicitly, depending on your exact requirements:
var dt = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
.AddMilliseconds(1286294501433);

What is the easiest way to subtract time in C#?

I'm trying to put together a tool that will help me make work schedules. What is the easiest way to solve the following?
8:00am + 5 hours = 1:00pm
5:00pm - 2 hours = 3:00pm
5:30pm - :45 = 4:45
and so on.
These can all be done with DateTime.Add(TimeSpan) since it supports positive and negative timespans.
DateTime original = new DateTime(year, month, day, 8, 0, 0);
DateTime updated = original.Add(new TimeSpan(5,0,0));
DateTime original = new DateTime(year, month, day, 17, 0, 0);
DateTime updated = original.Add(new TimeSpan(-2,0,0));
DateTime original = new DateTime(year, month, day, 17, 30, 0);
DateTime updated = original.Add(new TimeSpan(0,-45,0));
Or you can also use the DateTime.Subtract(TimeSpan) method analogously.
Check out all the DateTime methods here: http://msdn.microsoft.com/en-us/library/system.datetime.aspx
Add Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.
AddDays Returns a new DateTime that adds the specified number of days to the value of this instance.
AddHours Returns a new DateTime that adds the specified number of hours to the value of this instance.
AddMilliseconds Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.
AddMinutes Returns a new DateTime that adds the specified number of minutes to the value of this instance.
AddMonths Returns a new DateTime that adds the specified number of months to the value of this instance.
AddSeconds Returns a new DateTime that adds the specified number of seconds to the value of this instance.
AddTicks Returns a new DateTime that adds the specified number of ticks to the value of this instance.
AddYears Returns a new DateTime that adds the specified number of years to the value of this instance.
This works too:
System.DateTime dTime = DateTime.Now();
// tSpan is 0 days, 1 hours, 30 minutes and 0 second.
System.TimeSpan tSpan = new System.TimeSpan(0, 1, 3, 0);
System.DateTime result = dTime + tSpan;
To subtract a year:
DateTime DateEnd = DateTime.Now;
DateTime DateStart = DateEnd - new TimeSpan(365, 0, 0, 0);
Hi if you are going to subtract only Integer value from DateTime then you have to write code like this
DateTime.Now.AddHours(-2)
Here I am subtracting 2 hours from the current date and time
Use the TimeSpan object to capture your initial time element and use the methods such as AddHours or AddMinutes. To substract 3 hours, you will do AddHours(-3). To substract 45 mins, you will do AddMinutes(-45)
try this
namespace dateandtime
{
class DatesTime
{
public static DateTime Substract(DateTime now, int hours,int minutes,int seconds)
{
TimeSpan T1 = new TimeSpan(hours, minutes, seconds);
return now.Subtract(T1);
}
static void Main(string[] args)
{
Console.WriteLine(Substract(DateTime.Now, 36, 0, 0).ToString());
}
}
}
TimeLeftToOpen= new TimeSpan(TimeLeftToOpen.Hours, TimeLeftToOpen.Minutes, TimeLeftToOpen.Seconds - 1);

Categories