Change format of DateTime without converting to string - c#

I'm new in c# and I have Datetime variable like:
DateTime startingDate
value = 8/8/2018 4:16:18 PM
I want value like 8/8/2018, how can I just drop hours minutes seconds and PMvalue without converting to string? because I'm forced DateTime type for another thing.

In C# (as in many other languages) there is no separate Date and Time, it's just DateTime. Regardless of that though, there are many use cases where you only need a date. In C# it's assumed that if you just need 8/8/2018 then in reality you are working with 8/8/2018 0:00:00.000.
If you need to work with just the Date but still keep it as a DateTime, then the most straightfoward method is to use .Date (i.e. startingDate.Date). This can get a little confusing since the default .ToString() for DateTime represents it (in whatever is the cultural norm for your computer) as Month/Day/Year Hour:Minute:Second AM/PM.
Also, for further clarification, DateTime is an object that has a variety of different properties (Year, Month, Day, Hour, Minute, Second etc), so thinking of it having a "format" is incorrect. It's a collection of things that together make up a Date and/or Time.

Related

DateTime timezone in .NET seems to be wrong?

I have been having some fun with DateTime parsing from strings in .NET MVC, and I have identified some curious behaviour. Look at this test:
[Test]
public void DoesItWork()
{
DateTime theTime = DateTime.Now;
DateTime theUTCTime = theTime.ToUniversalTime();
Assert.IsTrue(theTime==theUTCTime);
}
I'm in the UK right now, and its BST, so I expect the UTC time to be an hour behind the value of DateTime.Now. So it is. But when I call .ToUniversalTime() on my initial date time, as well as subtracting an hour, the value's Kind property is also updated - from Local to Utc. This is also what I would expect.
But when I come to compare the values of these two DateTimevariables, the equality operator doesn't take account of the different Kind values, and simply reports they're different values. To me, this seems flat out wrong.
Can anyone elucidate why it works this way?
According to MSDN and MSDN2 when you compare two DateTime values:
Remarks
To determine the relationship of the current instance to value, the CompareTo method compares the Ticks property of the current instance and value but ignores their Kind property. Before comparing DateTime objects, make sure that the objects represent times in the same time zone. You can do this by comparing the values of their Kind properties.
Remarks
The Equality operator determines whether two DateTime values are equal by comparing their number of ticks. Before comparing DateTime objects, make sure that the objects represent times in the same time zone. You can do this by comparing the values of their Kind property.
So it's correct.
Link to DateTime.Kind Property and again from the remark:
The Kind property allows a DateTime value to clearly reflect either Coordinated Universal Time (UTC) or the local time. In contrast, the DateTimeOffset structure can unambiguously reflect any time in any time zone as a single point in time.
UPDATE
Regarding your comment. IMHO it is expected behavior. Because usually, you don't need to compare two DateTimes from different time zone. If you need to do this although, you have to use DateTimeOffset DateTimeOffset Structure which is:
Remarks
The DateTimeOffset structure includes a DateTime value, together with an Offset property that defines the difference between the current DateTimeOffset instance's date and time and Coordinated Universal Time (UTC). Because it exactly defines a date and time relative to UTC, the DateTimeOffset structure does not include a Kind member, as the DateTime structure does. It represents dates and times with values whose UTC ranges from 12:00:00 midnight, January 1, 0001 Anno Domini (Common Era), to 11:59:59 P.M., December 31, 9999 A.D. (C.E.).

How to convert Datetimes into UTC based timing values to compare timings- C#

I've string (variable is fileDate) with Date values in the following format:
2/12/2011 11:58 AM
Now I want to convert this to a date and then to UTC time based as I've problems in comparing dates in different machines, so *I always want to convert all strings (which are getting compared) to Utc_date values.*
I tried this code below but it did not work as I'm not able to convert the above string to Datetime based (as it does not have seconds).
DateTime date = Convert.ToDateTime(fileDate);
date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
fileDate = date.ToString("MM/dd/yyyy hh:mm tt");
Above did not work showing FormatException.
Can you pl help?
To start with, I'd suggest using DateTime.ParseExact or TryParseExact - it's not clear to me whether your sample is meant to be December 2nd or February 12th. Specifying the format may well remove your FormatException.
The next problem is working out which time zone you want to convert it with - are you saying that 11:58 is a local time in some time zone, or it's already a UTC time?
If it's a local time in the time zone of the code which is running this, you can use DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal to do it as part of parsing.
If it's already a universal time, use DateTimeStyles.AssumeUniversal
If it's a local time in a different time zone, you'll need to use TimeZoneInfo to perform the conversion.
Also, if it's a local time you'll need to consider two corner cases (assuming you're using a time zone which observes daylight saving time):
A local time may be skipped due to DST transitions, when the clocks go forward. So if the clocks skip from 1am to 2am, then 1:30am doesn't exist at all.
A local time may be ambiguous due to DST transitions, when the clocks go back. So if the clocks go back from 2am to 1am, then 1:30am occurs twice at different UTC times - which occurrence are you interested in?
You should decide how you want to handle these cases, and make sure they're covered in your unit tests.
Another option is to use my date and time library, Noda Time, which separates the concepts of "local date/time" and "date/time in a particular time zone" (and others) more explicitly.
you should be using DateTime.ParseExact to get the value into a proper DateTime instance, and then you can use .ToUniversalTime() to get the UTC time (this would be with respect to the difference of time as in your server machine)
you can use :
DateTime.Now.ToUniversalTime();
i don't mean to say to you should use "DateTime.Now" but you get the point that as a part of the DateTime object you have a method to transform it to Universal time
http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx

Change date to Universal Time Format changes my date wrongly I can't get error

I am trying to simply change the date format from the datatable to universal time format but it formats it wrongly as if I have date for August 7 it changed it to August 8 after formatting it to universal date time. My code for formatting date is,
DateVar[runs] = DateTime.Parse(Convert.ToString(output.Tables[0].Rows[runs][0])).ToUniversalTime().ToString();
Don't get in to code its correct and its a part of loop so "run" is loop and output is data set having one table I have first data in table is "Sunday, August 07, 2011 10:52 PM" and it was converted to "8/8/2011 5:52:00 AM" after implementing universal time format.
Hopes for your suggestions
Universal time isn't a format - it's a time zone, effectively. It's not clear what you're trying to do, but converting a "local" DateTime to "universal" DateTime will usually change the time. If you don't want that to happen, don't call ToUniversalTime.
It's a pity that the .NET date/time API isn't as clear as it could be - the DateTime type itself has some horrible ambiguities about it. I'm trying to improve the situation with my Noda Time project, but you will need to understand what time zones are about etc.
Personally I would suggest not using simply DateTime.Parse or just calling ToString unless you're absolutely sure that the default format is what you want. I usually call DateTime.ParseExact and specify the expected format (and usually CultureInfo.InvariantCulture unless it's a user-entered string) - and likewise I provide a format string to the ToString call.
In your code you're simply converting a string to a string - what are you attempting to accomplish? If you're just trying to change the format (e.g. to dd/MM/yyyyTHH:mm:ss) then you don't need to call ToUniversalTime but you do need to provide the format string.
I suggest you split your code out into several statements to help you debug this (and for general code clarity):
Fetch the string from the DataTable, if you really need to (if it's already a DateTime, there's no point in converting it to a string and then back again)
Parse the string (again, assuming you need to)
Perform any conversions you need to
Format the DateTime with an explicit format string
Now if any single operation is causing a problem, you can isolate it more easily.
If I run ToUniversalTime() from Greenwich it will give same time but if i do it while I live some where else it will get an offset date time object of + or - hours depending on position.

how to specify day and month but not the year in DateTime in c#

Hi All
I am using DateTime class to do some processing on dates. The issue I am facing is that in some cases i would like it to initialize to date component excluding the year part of date. How do i do that?
Example: For date 11/March/2011, I only want to store 11-March. How do i do that?
Thanks
You can't with the DateTime class (actually a struct). You can ignore the year value in your processing, however. You could also create your own class to do what you want.
You can't to that with DateTime because it is used to represent a specific moment time.
Since a day and a month are not sufficient information to represent a date, you can't store these information in DateTime only.
Maybe you should explain further what you would like to achieve.
If your concern is about outputting/formatting this date please view the following document in MSDN for format options you can apply to the toString() method of DateTime.
MSDN: Standard Date and Time Format Strings
Something you could do if you are really forced to use DateTime is to rebase each entered date to a specific year, although I can't see how this should make any sense, especially when it comes to leap years
One way you can do this is to use the TimeSpan structure. Then you can use that on top of any DateTime calculations you need

Is this a correct use of DateTime? Will it work for all timezones?

So,
I'm storing a DateTime object as a private member on an object. This private member is set on object creation like so:
this.mCreateDate = DateTime.UtcNow.ToUniversalTime();
Now, later on in the application, I want to see how long the object has been alive for. This could be many weeks (this is a long running web app).
I'm getting the object lifetime like so:
DateTime now = DateTime.UtcNow.ToUniversalTime();
TimeSpan objectLifetime = now.Subtract(Foo.CreateDate);
// Output formatted time span
Does this all look correct?
First, calling ToUniversalTime() on DateTime.UtcNow is redundant, since .net 2.0, no conversion happens if the "Kind" of the source DateTime object is "Utc".
Other than that, this looks fine.
This seems correct, and you're following the golden rule of DateTime: Use UTC, display in local!
Your approach seems correct to me although I think it is more appropriate to use the DateTimeOffset structure, which is new since .NET 3.5.
I quote Anthony Moore:
Use DateTimeOffset whenever you are referring to an exact point in time. For example, use it to calculate "now", transaction times, file change times, logging event times, etc. If the time zone is not known, use it with UTC. These uses are much more common than the scenarios where DateTime is preferred, so this should be considered the default.
Use DateTime for any cases where the absolute point in time does not apply: e.g. store opening times that apply across time zones.
Use DateTime for interop scenarios where the information is a Date and Time without information about the time zone, e.g. OLE Automation, databases, existing .NET APIs that use DateTime, etc.
Use DateTime with a 00:00:00 time component to represent whole dates, e.g. Date of irth.
Use TimeSpan to represent times of day without a date.
So you could simply write:
this.mCreateDate = DateTimeOffset.Now;
//...
TimeSpan lifeTime = DateTimeOffset.Now - Foo.CreateDate;

Categories

Resources