Converting String Format "yyyy-MM-ddTHH:mm:ss.fffZ" to DateTime - c#

I know this question has been asked a number of different ways, and I have looked at them all and none of the solutions seem to work for me. So, I am hoping that maybe you guys can give me a quick hand.
The input string is: "2000-01-01T12:00:000Z". I need to take that input string and convert it to DateTime so that it can be stored in the database.
I have been using ParseExact, but I keep getting the not recognized date string exception. Where am I going wrong?
inValue.LatestDepartTime = "2000-01-01T12:00:000Z";
DateTime _latestDepartTime = DateTime.ParseExact(inValue.LatestDepartTime, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);

Your format string needs to exactly match the input.
That includes the literal T and Z characters.

Use yyyy-MM-dd'T'HH:mm:ss.fff'Z'
The code is:
public DateTime convertIsoToDateTime (string iso)
{
return DateTime.ParseExact(iso, "yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture);
}

You need to include \\T and \\Z in your format string to match the literals T and Z.

You need to put single quotes around the T and Z:
DateTime parsedDateTime;
DateTime.TryParseExact(obj, "yyyy-MM-dd'T'HH:mm:ss'Z'", null, System.Globalization.DateTimeStyles.None, out parsedDateTime);
return parsedDateTime;

You don't specify the T in the pattern.
That said, you may want to have a look at the XmlConvert class, which provides the methods for converting this format.

Related

How to parse this DateTimeOffset?

I'm getting a DateTimeOffset string as "2018-10-16T193850+0200", but I think it's none of the standard formats. Mainly, the "+0200" part is not standard, because it lacks the colon.
What format do I have to specify to parse DateTimeOffsets like this? thank you!
You can use ParseExact:
DateTimeOffset offsetDate = DateTimeOffset.ParseExact(
"2018-10-16T193850+0200",
"yyyy-MM-dd'T'HHmmsszzzz",
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.None);
Read: Custom Date and Time Format Strings
Unfortunately setting DateTimeInfo.TimeSeparator to empty string won't help.
But you can use DateTimeOffset.ParseExact as follows:
DateTimeOffset date = DateTimeOffset.ParseExact("2018-10-16T193850+0200", "yyyy'-'MM'-'dd'T'HH''mm''ss''K", CultureInfo.InvariantCulture.DateTimeFormat);
The trick is to specify 'K' format specifier in order to accept all kinds of offsets. Additionally to the above date string the following will be parsed correctly as well:
"2018-10-16T193850Z" - UTC
"2018-10-16T193850" - local time
EDIT
My answer is similar to Tim Schmelter's one, except by the 'K' part.

Convert to datetime from Oracle

i know there are a lot of similar questions, but I couldn't find what I was looking for.
Here is my oracle date:
string testdate= "2014-01-07 15:00:00.0000000";
And here is how I tried to convert to datetime:
DateTime.ParseExact(testdate, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)
This throws a format exception. Any ideas?
My quick test also throws the string not valid datetime exception. Quick test:
Console.WriteLine(DateTime.ParseExact(testdate, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture).ToShortDateString());
I'd start by trying to avoid getting it as a string in the first place. Make sure you're using the appropriate data type in Oracle, and you should be able to call GetDateTime on the appropriate DataReader (or whatever you're using).
If you must parse it as text, then you need to specify a format which matches the value - so use 7 fs instead of 3, given that your value has ".0000000" at the end.
DateTime.ParseExact(testdate, "yyyy-MM-dd HH:mm:ss.fffffff",
CultureInfo.InvariantCulture)
But again, I'd strongly urge you to avoid having to deal with the value as text at all.
Why use ParseExact at all? Reqular Parse seems to work.
var dt = DateTime.Parse("2014-01-07 15:00:00.0000000", CultureInfo.InvariantCulture);
// Prints out 2014-01-07T15:00:00.0000000
Console.WriteLine(dt.ToString("o"));

How to create a .NET DateTime from ISO 8601 format

I've found how to turn a DateTime into an ISO 8601 format, but nothing on how to do the reverse in C#.
I have 2010-08-20T15:00:00Z, and I want to turn it into a DateTime object.
I could separate the parts of the string myself, but that seems like a lot of work for something that is already an international standard.
This solution makes use of the DateTimeStyles enumeration, and it also works with Z.
DateTime d2 = DateTime.Parse("2010-08-20T15:00:00Z", null, System.Globalization.DateTimeStyles.RoundtripKind);
This prints the solution perfectly.
Although MSDN says that "s" and "o" formats reflect the standard, they seem to be able to parse only a limited subset of it. Especially it is a problem if the string contains time zone specification. (Neither it does for basic ISO8601 formats, or reduced precision formats - however this is not exactly your case.) That is why I make use of custom format strings when it comes to parsing ISO8601. Currently my preferred snippet is:
static readonly string[] formats = {
// Basic formats
"yyyyMMddTHHmmsszzz",
"yyyyMMddTHHmmsszz",
"yyyyMMddTHHmmssZ",
// Extended formats
"yyyy-MM-ddTHH:mm:sszzz",
"yyyy-MM-ddTHH:mm:sszz",
"yyyy-MM-ddTHH:mm:ssZ",
// All of the above with reduced accuracy
"yyyyMMddTHHmmzzz",
"yyyyMMddTHHmmzz",
"yyyyMMddTHHmmZ",
"yyyy-MM-ddTHH:mmzzz",
"yyyy-MM-ddTHH:mmzz",
"yyyy-MM-ddTHH:mmZ",
// Accuracy reduced to hours
"yyyyMMddTHHzzz",
"yyyyMMddTHHzz",
"yyyyMMddTHHZ",
"yyyy-MM-ddTHHzzz",
"yyyy-MM-ddTHHzz",
"yyyy-MM-ddTHHZ"
};
public static DateTime ParseISO8601String ( string str )
{
return DateTime.ParseExact ( str, formats,
CultureInfo.InvariantCulture, DateTimeStyles.None );
}
If you don't mind parsing TZ-less strings (I do), you can add an "s" line to greatly extend the number of covered format alterations.
using System.Globalization;
DateTime d;
DateTime.TryParseExact(
"2010-08-20T15:00:00",
"s",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal, out d);
Here is one that works better for me (LINQPad version):
DateTime d;
DateTime.TryParseExact(
"2010-08-20T15:00:00Z",
#"yyyy-MM-dd\THH:mm:ss\Z",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out d);
d.ToString()
produces
true
8/20/2010 8:00:00 AM
It seems important to exactly match the format of the ISO string for TryParseExact to work. I guess Exact is Exact and this answer is obvious to most but anyway...
In my case, Reb.Cabin's answer doesn't work as I have a slightly different input as per my "value" below.
Value: 2012-08-10T14:00:00.000Z
There are some extra 000's in there for milliseconds and there may be more.
However if I add some .fff to the format as shown below, all is fine.
Format String: #"yyyy-MM-dd\THH:mm:ss.fff\Z"
In VS2010 Immediate Window:
DateTime.TryParseExact(value,#"yyyy-MM-dd\THH:mm:ss.fff\Z", CultureInfo.InvariantCulture,DateTimeStyles.AssumeUniversal, out d);
true
You may have to use DateTimeStyles.AssumeLocal as well depending upon what zone your time is for...
This works fine in LINQPad4:
Console.WriteLine(DateTime.Parse("2010-08-20T15:00:00Z"));
Console.WriteLine(DateTime.Parse("2010-08-20T15:00:00"));
Console.WriteLine(DateTime.Parse("2010-08-20 15:00:00"));
DateTime.ParseExact(...) allows you to tell the parser what each character represents.

date from string help. I can convert to the string I want, but I can't convert back

I have a string I need to convert back to a date. I can call .ToString("yyyyMMdd") and get the string i want. My question is how can I convert that back into a date? I'm trying something like the following with no luck.
DateTime d;
var formatInfo = new DateTimeFormatInfo {ShortDatePattern = "yyyyMMdd"};
if (DateTime.TryParse(details.DetectionTime.Date, formatInfo, DateTimeStyles.None, out d))
{
lit.Text = d.ToShortTimeString(); //would like 07/30/2010 as the text
}
I've never used DateTimeFormatInfo before if that isn't obvious. Can someone point me in the right direction. I know I could probably use substring and create a new DateTime(y, m, d) etc... I'm just wondering since c# interpreted .ToString() correctly, if it can't derive a date from the very same string it output.
The reverse of DateTime.ToString("yyyyMMdd") is DateTime.TryParseExact, passing "yyyyMMdd" as a format string.
IFormatProvider is a bit of a red herring. You'll normally pass either :
Thread.CurrentThread.Culture, if you're parsing a date typed by the user, when you should obey the user's date preferences
Or CultureInfo.InvariantCulture, if you're parsing a date provided by a program, when your behaviour shouldn't depend on the preferences the user has set up
Use d.ToString("MM/dd/yyyy")
For more options check out http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx
Edit: Read it wrong
Use DateTime.Parse() to parse the string to a datetime.
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
You can also use DateTime.TryParse to see if the string is able to convert to a date first.
http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx
Alternatively you can also use Convert.ToDateTime()
If you want the DateTime variable back after sending it to a string, save yourself the trouble and just cache or pass the actual DateTime variable around scopes to wherever you need it later and don't bother converting the text back into a DateTime class..
Sorry I just realized this doesn't answer your request, so what you're looking for is:
DateTime.ParseExact(someDateTime, "the format string you used to .tostring generating the string", null);
Convert.ToDateTime("07/30/2010");
I'm assuming you mean to convert a string to a DateTime format. If so use this:
DateTime yourStringConverted = Convert.ToDateTime( yourString );

How do I keep the 0's in a Date

I am trying to figure out how it is that I can keep the 0's or add them when I grab a date.
What Im getting is this:
6/15/2010
What I'm tring to get is:
06/15/2010
I have added it so that it checks the length to and if its less than 6 (im stripping the "/") it pads the left side. That solves the issue when the month is a single digit, but what about when the date is a single digit.
My ultimate goal is to have a date such as:
1/1/2010
read out like:
01/01/2010
Any suggestions would be greatly appreciated.
Use a custom format : dd/MM/yyyy, or in your case MM/dd/yyyy. Note the capital M, the small m gets you the minutes.
string s = DateTime.Now.ToString("MM/dd/yyyy");
You need to use a custom DateTime format string:
string str = someDate.ToString("dd/MM/yyyy");
It depends on the format of date you are using.
For instance, dd/MM/yyyy will produce 01/05/2009 and d/M/yyyy would produce 1/5/2009
A complete reference can be found there : http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
You want something like this:
string myDate = "1/1/2010";
DateTime date = DateTime.Parse(myDate);
string formattedDate = date.ToString("MM/dd/yyyy");
If the starting date is some other unrecognized format you could use DateTime.ParseExact();
Use DateTime.ParseExact() to parse the string into a valid datetime object and then use DateTime.ToString("dd/MM/yyyy") to get result in desired format.

Categories