C# DateTime.ParseExact for "2012-09-03T06:35:31Z" - c#

In C# I am trying to convert "2012-09-03T06:35:31Z" into a Datetime:
Date = DateTime.ParseExact( "2012-09-03T06:35:31Z", ???);
I'm not sure how to parse the rest of the function

//using System.Globalization; should be at top
Date = DateTime.ParseExact("2012-09-03T06:35:31Z", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal)
See the custom date and time format documentation. This is similar to the sortable format, but with a Z on the end.

You don't say whether the format is specified as always being in UTC and indicated with Z.
If that is the case, then
DateTime.ParseExact(
yourDateString, #"yyyy\-MM\-ddTHH:mm:ss\Z",
CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal)
Will do fine.
However, if UTC is not specified by the standard you are working to, the input you have to deal with could also be e.g. 2012-09-03T06:35:31+05:00 or 2012-09-03T06:35:31+0500 depending on the ISO 8601 format in use - Z is a special case within that format for +00:00. If you need to handle that possibility, then you want to first create a DateTimeOffset, and then obtain the equivalent UTC DateTime from it:
DateTimeOffset.ParseExact(yourDateString,
new string[]{#"yyyy\-MM\-ddTHH:mm:sszzz",#"yyyy\-MM\-ddTHH:mm:ss\Z"},
CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).UtcDateTime
Note that we still use AssumeUniversal. This is because the second format is saying "A Z will appear here", but the method then ignores it, so we have to explicitly have this form interpreted as UTC. With the first format though, the zzz will give the timezone, and hence the AssumeUniversal is ignored. (Or to put it another way, it's assuming universal until told otherwise, and that format does indeed say otherwise).

Looks like you are trying to parse an Xml date. If this is the case I would suggest using the XmlConvert class...
Date = System.Xml.XmlConvert.ToDateTime("2012-09-03T06:35:31Z", XmlDateTimeSerializationMode.Local);
You will need to change the XmlDateTimeSerializationMode to the appropriate value.

Related

Format Localized DateTime C#

I want to format localized date into format. e.g yyyyMMdd OR ddMMyyyy OR MMddyyyy based on system date format. Below is what I have tried and it is working , but need efficient way to do same.
DateTime.Now.ToLocalTime().Date.ToString().Replace("/","").Replace(":","").Replace(" ","").Replace("-","")
You can use the ToString overload(read also):
DateTime.Now.ToLocalTime().ToString("yyyyMMdd")
(why you think you need ToLocalTime here? Now always returns the local time)
cant use .ToString("yyyyMMdd") because i need different result
depending on what my system date format is. if system date time is
dd-MM-yyyy i want ddMMyyyy, if its yyyy-MM-dd then expected result is
yyyyMMdd
Then you either stick with your current approach or use something like this:
DateTime.Now.ToString("d").Replace(DateTimeFormatInfo.CurrentInfo.DateSeparator, "")

DateTime.TryParse() not working with formatted date dd/MM/yyyy

This code returns (min time 1/1/0001 12:00:00 AM) not Date.Time.Now . Try Parse works for MM/dd/yyyy but not dd/MM/yyyy . Any suggestions
Here is code
DateTime start, end;
DateTime.TryParse(EPSDate12.Text, out start);
string TNow = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"); // Works
// string TNow = DateTime.Now.ToString();// works but gives MM/dd/yyyy as expected
DateTime.TryParse(TNow, out end); // No. gives min time (1/1/0001 12:00:00 AM)
Use TryParseExact and supply the format string.
Also examine the return value from TryParseExact to know if it failed or not (it returns a bool)
I see "EPSDate12.Text" which i suspect may be a TextBox: If you're doing this in a UI, make life easy and use a DateTimePicker - you can set the format, the user can type into them just like a textbox, but they don't accept invalid inputs, and all you have to do is get the .Value property which gives you a DateTime
As to why your attempts to parse the string you made don't work, I think it most likely that the date format Parse is using (which is based on the culture settings of the executing thread) is not the same format as the string you prepared using your forced format. Either make sure your forced format is matched to the current culture, or use a culture that matches your forced format, or use [Try]ParseExact to force the format for parsing like you did when creating the string
See https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parse?view=net-5.0#Culture for more info
The datetime value is internally the same. But, ToString() return value, depends on
the local machine culture setup.
Reference article
The default DateTime.ToString() method returns the string
representation of a date and time value using the current culture's
short date and long time pattern. The following example uses the
default DateTime.ToString() method.
For en-US culture(MM/dd/yyyy hh:mm:ss) , it will be in
7/28/2021 11:37:40 AM
If you want to see in en-GB(dd/MM/yyyy hh:mm:ss), you can apply conversion as given below:
var culture = new CultureInfo("en-GB");
MessageBox.Show($"{DateTime.Now.ToString(culture)}");
28/07/2021 11:45:09 AM
you can also specify exact custom format, in which you want to display.
MessageBox.Show($"{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss tt")}");
28/07/2021 11:45:09 AM
Thanks for suggestions . Yes DateTime.TryParse is not working and it could be format issue
This line of code.
string TNow = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
generates
29/07/2021 14:49:03
which looks OK but fails TryParse

How to make datetime.now return date in UK format with c#

I want datetime.now to return the datetime object in UK format. It does so on my local computer but when I upload the code to the server it does it in US format
DateTime doesn't have any format associated with it. Formatting is just for presentation. You can do:
string formattedDate = DateTime.Now.ToString(CultureInfo.CreateSpecificCulture("en-GB"));
Or supply a specific/custom format like:
string formattedDate = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
I want datetime.now to return the datetime object in UK format.
There's no such concept, any more than an int is a value "in hex" or "in decimal". A DateTime is just a DateTime - you can specify the format when you convert it to a string. It's really important to understand the difference between an inherent value, and what it looks like after it's converted to text - very few types are aware of a custom, modifiable format to use when converting themselves - it's either provided externally (as for DateTime, numbers etc) or simply fixed.
Before you convert start hard-coding a UK format though, I would strongly advise you to consider exactly what you're doing:
Ideally, avoid the conversion in the first place. A lot of the time, string conversions are unnecessary and can be problematic.
Is the text going to be consumed by another machine? Use an ISO-8601 standard format.
Is the text going to be consumed by a person? Use their culture rather than some arbitrary one you decide on.
... Or display it in a dedicated control...
You can use the overload of the ToString method: ToString("dd/MM/yyyy"), or: ToString("yy/MMM/dd"), etc. etc.
Read more about it here: https://msdn.microsoft.com/en-us/library/zdtaw1bw%28v=vs.110%29.aspx
Also sounds to me that you might want to configure your (UI-)Culture in the web.config? Then it will always be in the same format regardless of the culture of your US/Japanese/european server culture..
More about that here: https://msdn.microsoft.com/en-us/library/bz9tc508%28v=vs.140%29.aspx
LogDate = DateTime.UtcNow.AddHours(1);

Convert date in string to DateTime with same format

I have a string that has a date stored in it.
String date = "03-05-2013 00:00:00";
I parsed it to Datetime as follows:
DateTime Start = DateTime.Parse(date);
Start.ToString() gave me "3/5/2013 12:0:00 AM"
I also used:
DateTime Start = DateTime.ParseExact(date,"dd-MM-yyyy HH:mm:ss",CultureInfo.InvariantCulture);
Then, Start.ToString() gave me "3/5/2013 12:0:00 AM", which is the exact same result as the previous one. I need to keep the original formatting. How may I do it? Thanks.
The format you parse with does not dictate how the DateTime is formatted when you convert the date back to a string. When you call ToString on a date it pulls the format from the current culture of the thread your code is executing on (which defaults to the culture of the machine your on).
You can override this by passing the format into ToString() i.e.
Start.ToString("dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
See Custom Date and Time Formats.
You need to pass the format in the ToString() call.
Start.ToString("dd-MM-yyy HH:mm:ss");
I need to keep the original formatting.
Then you need to apply the same pattern again when you call ToString:
string formatted = Start.ToString("dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
(Note that you should specify the same culture when formatting as you did when parsing, to avoid things like the time separator from changing.)
Note that for some formats this still might not give the exact original representation - if you're using a format which includes the text for a month, for example, that would match case-insensitively, so input including "MARCH" would be reformatted as "March".
A DateTime value is just a date and time (and a "kind", but that's another story) - it doesn't maintain a textual representation any more than an integer does. It's important to differentiate between the inherent data in a value and a textual representation of that data. Most types which have multiple possible textual representations have no notion of keeping "the original representation" alongside the data.

datetime.parseexact returns wrong month

Here is my code:
a.dateFrom = DateTime.ParseExact(x, "dd/mm/yyyy", null);
And x has value of: 08/03/2012
However, a.dateFrom has value of 08/01/2012. Why?
You should use MM as format for month
As ionden notes, you should have a format of
"dd/MM/yyyy"
Currently you're parsing the second part as minutes (as that's what mm means).
See the documentation for custom date and time format strings for more information. I'd also strongly encourage you to consider using the invariant culture for parsing - if you're using a custom format string, that usually means you don't want to treat the input in a culture-sensitive fashion at all.

Categories

Resources