I am looking for a way to correctly display localized duration of time larger than 24 hours in C# and Delphi. I mean, the DateTime type often has such string function provided, but time span does not, why?
And I don't even know what is a correct format for non localized time span.
e.g. for a duration of 2 days 10 hours 30 minutes.
I found some would display such time span as 2.10:30:00 or 2:10:30:00 or 2 10:30:00.
Please help, thanks.
For invariant culture (non localized):
myDateTime.ToString(CultureInfo.InvariantCulture)
Otherwise, just use myDateTime.ToShortDateString() or .ToLongDateString().. it will use :
System.Threading.Thread.CurrentThread.CurrentUICulture in that case..
or if you had something specific in mind, you could do
var myCulture = CultureInfo.GetCultureInfo("en-GB");
dt.ToString(myCulture);
EDIT
For TimeSpans:
Example:
DateTime dt1 = new DateTime(2012, 7, 17, 12, 30, 0);
DateTime dt2 = new DateTime(2012, 7, 18, 14, 40, 0);
TimeSpan ts = dt2 - dt1;
string s = ts.ToString("G", CultureInfo.InvariantCulture);
More examples here: http://msdn.microsoft.com/en-us/library/dd784379.aspx
EDIT 2:
More info on TimeSpan format strings:
http://msdn.microsoft.com/en-us/library/ee372286.aspx
You could follow ISO 8601, a PDF of the spec can be found here. See section 4.4.3 Duration
However, using the convention as lined out in this document looks fairly complicated to me, because according to this specification, you need to include context about when the time interval takes place:
The duration of a calendar year, a calendar month, a calendar week or
a calendar day depends on its position in the calendar. Therefore,
the exact duration of a nominal duration can only be evaluated if the
duration of the calendar years, calendar months, calendar weeks or
calendar days used are known.
If the actual moment at which the time span takes place is not relevant for your application, then maybe it would be good enough to forget about the year and month parts and just stick with the format nnDTnnHnnMnnS. That should not be too hard to achieve using the standard TimeSpan methods.
Update:
Reading a bit further, this standard does not seem to be applicable to your problem after all:
Duration is used as a component in representations of time intervals
and recurring time intervals, representation of duration as such is
not facilitated by this International Standard.
I will just leave the answer here to avoid anybody else walking into this dead end like I did, or if you think 'sort of following a standard' is good enough...
Related
This question already has answers here:
How do you convert epoch time in C#?
(14 answers)
Closed 2 years ago.
I have a simple DateTime object, equal to the date: 11/1/2020 8:11:14 AM.
I want to convert it to milliseconds so I do:
myTimestamp?.Ticks / TimeSpan.TicksPerMillisecond.
I get 63739786274788, which seems correct from the pure calculation perspective.
However, when I input it into one of the online converters to validate, I get the date Wed Nov 01 3989 01:11:14, which is of course way off.
Questions:
What is this number 63739786274788 if not time in ms?
How do I get "normal" timestamp in ms?
In .NET, DateTime ticks are based on an epoch of 0001-01-01T00:00:00.0000000. The .Kind property is used to decide whether that is UTC, local time, or "unspecified".
Most online converters, such as the one you linked to, are expecting a Unix Timestamp, where the value is based on an epoch of 1970-01-01T00:00:00.000Z. It is always UTC based. (The precision varies, both seconds and milliseconds are commonly used.)
If you want to get a milliseconds-based Unix Timestamp From .NET, instead of dividing you should use the built-in functions DateTimeOffset.FromUnixTimeMilliseconds and DateTimeOffset.ToUnixTimeMilliseconds. (There are also seconds-based versions of these functions.)
Assuming your input values are UTC-based:
DateTime dt = new DateTime(2020, 11, 1, 8, 11, 14, DateTimeKind.Utc);
DateTimeOffset dto = new DateTimeOffset(dt);
long timestamp = dto.ToUnixTimeMilliseconds();
// output: 1604218274000
DateTimeKind.Local will also work with this, assuming your values are indeed based on the computer's local time zone. DateTimeKind.Unspecified is a bit trickier, as you'll need to convert to a DateTimeOffset with a specific time zone using TimeZoneInfo first.
You could also construct the DateTimeOffset value directly, rather than go through DateTime at all.
Okay, so you start off dividing Ticks by TicksPerMillisecond (10,000)
As you can see, the number you generated is much larger than the current milliseconds:
63739786274788
1607363529803
The short answer is that Ticks are based off of 12:00:00 midnight January 1, 0001 and a your online calculator is based off of unix time, January 1, 1970. So that would explain why you're about 2,000 years off. If you subtracted the Ticks from a new DateTime(1970,1,1), then that would give you about the right number to satisfy the online calculator.
For more info, I would suggest reading through MS's docs on DateTime
I am trying to convert to Julian Time Stamp to Date Time. I have the following microseconds time stamp 212302469304212709. As i understand i need to add these milliseconds to the beginning of Julian Calendar (January 1, 4713 B.C., 12:00 (noon)). So i have the following method:
private DateTime GetDateTime(string julianTimeStamp)
{
var julianMilliseconds = Convert.ToDouble(julianTimeStamp)/1000;
var beginningOfTimes = new DateTime(1, 1, 1, 0, 0, 0, 0);
var dateTime = beginningOfTimes.AddMilliseconds(julianMilliseconds).AddYears(-4713).AddMonths(-1).AddDays(-1).AddHours(-12);
return dateTime;
}
Assume i pass 212302469304212709 string as the parameter. The expected result should be 2015/07(July)/01 00:08:24.212. Based on my method, i have almost the same result, but day is not 1, it is 6. Same problem for different time stamps i tested.
Could any one tell me what i am doing wrong? Thanks in advance.
Edited:
This is the exact date time i expect to receive: 2015(year) 7(month) 1(day) 0(hour) 8(minute) 24(second) 212(millisecond) 709(microsecond)
The given timestamp 212,302,469,304,212,709 μs when converted to days (just divide by 86,400,000,000) gives 2457204.505836 days (to six decimal places, which is the best I can do without a lot of extra trouble). Using the Multi Year Computer Interactive Almanac (MICA) written by the United States Naval Observatory, and putting in the free form date 2015(year) 7(month) 1(day) 0(hour) 8(minute) 24(second) 212(millisecond) 709(microsecond), the program calculates exactly the same day count (to six decimal places), proving the time stamp is an accurate Julian date.
One problem with the OP's calculation is trying to use the DateTime class before the earliest supported date, as pointed out by another poster. Also, the OP didn't say if 1 July 2015 was in the Julian or Gregorian calendar, but the MICA calculation proves it is in the Gregorian calendar. Since the OP is working in the Gregorian calendar, the epoch of Julian dates should be stated in the Gregorian proleptic calendar: Noon Universal Time, November 24, 4714 BC. The oft-quoted date January 1, 4713 BC is a proleptic Julian calendar date.
"Proleptic" means a date has been found by beginning at a modern date, who's calendar date is known with absolute certainty, and applying the rules of the chosen calendar backward until the desired date is reached, even though the desired date is before the chosen calendar was invented.
DateTime uses Gregorian calendar, so when you substract years, months and so on you are doing it with that calendar, not the Julian.
Unfortunately DateTime does not support dates before year 1. You can check the library in this post, maybe it helps you.
I am currently using the following date filter in my WebAPI application:
json.SerializerSettings.Converters.Add(
new IsoDateTimeConverter { DateTimeFormat = "dd-MM-yyyy hh:mm" });
I started to use this as my front end could not understand the dates. If I remember correctly it was due to the way milliseconds were formatted with too many digits.
What I need is to get the date into a format like this:
1288323623006
Can someone suggest how I can do this using the serializer. Is this different from the default?
You don't want to use IsoDateTimeConverter at all - you possibly want to use JavaScriptDateTimeConverter. That will convert it into new Date(...) with the right value - but I believe it really will include the new Date(...) part. If you don't want that, you'll probably need to write your own converter.
It shouldn't be too hard to write a converter - although you need to decide how to handle the different kinds of DateTime. For example, if you're asked to convert a DateTime with a Kind of Unspecified, do you want to assume it's actually already in UTC, or already in the system local time zone, or something else?
Once you've got an appropriate "instant" in time, you just need to find the number of milliseconds between that and the Unix epoch (1st January 1970 00:00:00, UTC) and convert that number of milliseconds into a string.
I think that's what you want
private static readonly long DatetimeMinTimeTicks = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks;
long b = (long)((Calendar1.SelectedDate).ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000;
I'm trying to find the time between two dates, one being the current day (Today) and the other, a user defined deadline.
I'm working with C# Windows Forms and I've used a "date time picker" so that the user can choose a deadline date and I've created a string called Today and used
string Today = System.DateTime.Today.ToString("dd-mm-yyyy");
as the current date. But I don't know how to find the length of time between these two points (since they're strings), my program is a simple "to do list" where task duration's are in days and weeks (the "yyyy" is just for aesthetic purposes, it can be removed if necessary).
I've had a look over the internet and all I can seem to find is how to do this with "DateTime"s, instead of strings (or am I missing something?).
Any help would be greatly apreciated.
Use the 'Value' property of your DateTimePicker to get the DateTime value and use DateTime.Now to get the DateTime value for the current time (in the local timezone).
If you are only subtracting dates (with no time component), access the Date property of both DateTime objects before subtracting.
DateTime userDate = dateTimePicker.Value.Date;
DateTime currentDate = DateTime.Now.Date;
TimeSpan difference = userDate.Subtract(currentDate); //assuming deadline is in the future
Don't use two strings - use the actual DateTime instances. Strings don't and can't "understand" dates - that's why the DateTime object exists.
When you subtract two dates from each other, you get a TimeSpan instance. This gives you the amount of time difference.
TimeSpan difference = date1 - date2;
I guess the following you are looking for:
Date1.Subtract(Date2).TotalTime
Following link will help you understand more
http://www.c-sharpcorner.com/UploadFile/DipalChoksi/DateDiff_CS_DC09132006172429PM/DateDiff_CS_DC.aspx
AS Oded mentions the string is not the best approach. DateTimes cann be substracted from one another and give you a TimeSpan that represents, well, that, a time span.
Here is an MSDN example that should clarify things.
DateTime departure = new DateTime(2010, 6, 12, 18, 32, 0);
DateTime arrival = new DateTime(2010, 6, 13, 22, 47, 0);
TimeSpan travelTime = arrival - departure;
Console.WriteLine("{0} - {1} = {2}", arrival, departure, travelTime);
// The example displays the following output:
// 6/13/2010 10:47:00 PM - 6/12/2010 6:32:00 PM = 1.04:15:00
I am using a JQuery plugin to render a calendar (http://arshaw.com/fullcalendar/). Problem is that the dates are one hour ahead. I have tried looking into the files to find out where this happens.
Can it be something with day light savings? I am pretty clueless. The dates from the database is correct, but once they are converted to a UNIX timestamp they are missing one hour.
I use this to convert my date to timestamp.
private double ConvertToTimestamp(DateTime value)
{
//create Timespan by subtracting the value provided from
//the Unix Epoch
var date = new DateTime(1970, 1, 1, 0, 0, 0, 0);
TimeSpan span = (value - date.ToLocalTime());
//return the total seconds (which is a UNIX timestamp)
return (double)span.TotalSeconds;
}
But i believe its not where the problems lies.
Thank you.
Is it possible that you live in a part of the world that observes Daylight Savings Time? That would explain why your dates are an hour ahead. Try skipping ahead to December and adding a few dates. Are they still an hour ahead?
I have had a similar problem and solved it with:
function _changeToLocal (localDate) {
return new Date( localDate.getFullYear(), localDate.getMonth(), localDate.getDate(),
localDate.getHours(), localDate.getMinutes() + localDate.getTimezoneOffset());
}
assuming it's a TimeZone related problem.
Günter
I just experienced a similar issue when moving from my dev box to Amazon EC2 for staging... The Regional Settings on my Amazon instance were set to US West Coast, not my timezone (Sydney, Australia).
Changing this, and then updating the locales of the built in accounts (Network Instance etc) resolved my problems with the dates being rendered incorrectly.