C# date format over 1 day - c#

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.

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);

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.

Converting TimeSpan Hours to DateTime

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!

Subtract time from date using format string

If I have a date and time in a DateTime object, can I remove say 10 minutes, or 24 hours etc from the date and time using a format string?
So if I have 1/1/1990 12:30:00pm and I wanted to remove 1 hour from it, can I use a format string?
edit
i need to store diary entries and the user can select a reminder type. so 1 hour before hand. so then i'd like to store the format string in a db that i can get and apply to a datetime to get the reminder date time
Something like this might do what you need. Not sure what you mean by subtracting an hour using a format string though.
DateTime dt = new DateTime(1990, 1, 1, 12, 30, 0);
string s = dt.Subtract(new TimeSpan(1, 0, 0)).ToString("MM/dd/yyyy hh:mm:ss tt")
Best way is to convert to a DateTime object and then back to the formatted string (if that's what you need):
var time = DateTime.Parse("1/1/1990 12:30:00pm");
time = time.AddMinutes(-10);
string timeString = time.ToString("MM/dd/yyyy hh:mm:ss tt");
You can use this in your query if you have..
DATE_SUB(date,INTERVAL expr unit)
Example:
YourDate = DATE_SUB(1/1/1990 12:30:00pm, INTERVAL 1 HOUR)
YourDate = DATE_SUB(1/1/1990 12:30:00pm, INTERVAL 12 MINUTE)
YourDate = DATE_SUB(1/1/1990 12:30:00pm, INTERVAL 45 SECONDS)

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