How to parse this string as a DateTime - c#

How can I parse the following string to DateTime with timezone?
Should I use CultureInfo? TimeZoneInfo? Or some other kind?
15.08.11 17:15:18.084867000 +02:00
I have try to use the following format:
var z = DateTime.Now.ToString("dd.MM.yy H:mm:ss.fffffff", CultureInfo.InvariantCulture);
But it threw an exception.

DateTime.ParseExact is what you want.
The actual format string you need is dd.MM.yy HH:mm:ss.FFFFFFF00 zzz
var dateTest = "15.08.11 17:15:18.084867000 +02:00";
var format = "dd.MM.yy HH:mm:ss.FFFFFFF00 zzz";
var returnDate = DateTime.ParseExact(dateTest, format, System.Globalization.CultureInfo.InvariantCulture);
The problem is that the fractional portion of seconds can only be 7 digits, and you need to pad the format string with zeros to cater for it.
There is a problem in that the last two digits of the seconds must be 00, otherwise the format won't work, so if the last two digits are ever anything other than 00 this format string won't work for you.
You'd need to parse out the entire string excluding the last to digits of the seconds but keeping the rest of the string intact. If one was to go to that much bother one might be as well off just manually parsing the string.
Sorry I can't be of more help.

Related

Convert Time Zone formatted datetime to local date time

Can someone point out this "20130913095509+1000" datetime represent which format in .NET.
I am able to parse this with following code
string test= "20130913095509+1000";
DateTime parseDt = DateTime.ParseExact(test,
"yyyyMMddhhmmsszzzz",
CultureInfo.InvariantCulture);
//For comparison
string output= parseDt.ToString("yyyyMMddhhmmsszzzz");
//output= 20130913095509+10:00
What is difference between "20130913095509+10:00" and "20130913095509+1000" in terms of Format in .NET.
A few things:
You'd be better to parse this as a DateTimeOffset rather than a DateTime. That way, the local time zone of the machine you are working on does not affect parsing behavior, and you don't need to worry about the madness that is DateTimeStyles or DateTimeKind. Since DateTimeOffset retains the offset you give it, it will survive the round trip from string to object back to string without changing.
zzzz is not a valid format specifier according to the documentation. It may appear to be honored by some implementations, but what's probably happening is that zzz and z are being interpreted separately, with the latter being ignored.
Unfortunately, there is not a format specifier that represents an offset with sign, hours, and minutes without a colon. zzz is the closest, which includes a colon when formatting with ToString, but treats it as optional when parsing with ParseExact. Thus you can use zzz in your format string, but you'll have to remove the : manually after a ToString call.
Putting this together:
string test = "20130913095509+0530";
DateTimeOffset dto = DateTimeOffset.ParseExact(test, "yyyyMMddHHmmsszzz", CultureInfo.InvariantCulture);
string output = dto.ToString("yyyyMMddHHmmsszzz").Remove(17,1);
Console.WriteLine(output); //=> 20130913095509+0530
Note that the format you are using is close to the ISO 8601 "basic" format, however that would include the T separator between the date and time components. If possible, you should consider inserting the T such that your data is ISO 8601 compliant.
string test = "20130913T095509+0530";
DateTimeOffset dto = DateTimeOffset.ParseExact(test, "yyyyMMdd'T'HHmmsszzz", CultureInfo.InvariantCulture);
string output = dto.ToString("yyyyMMdd'T'HHmmsszzz").Remove(18,1);
Console.WriteLine(output); //=> 20130913T095509+0530

Short Time with DateTime.ParseExact

I’m trying to parse a time. I’ve seen this question asked/answered here many times but not for this specific scenario. Here’s my code:
var time1 = DateTime.ParseExact("919", "Hmm", CultureInfo.InvariantCulture);
also
var time2 = DateTime.ParseExact("919", "Hmm", null);
both of these throw the same
"String was not recognized as a valid DateTime"
What I want is 9:19 AM.
For further info I also need to parse “1305” as 1:05 PM, this is working fine.
It seems to me I’m using the correct format. What am I overlooking?
I'm not sure there is any format that can handle this. The problem is that "H" can be either one digit or two, so if there are two digits available, it will grab both - in this case parsing it as hour 91, which is clearly invalid.
Ideally, you'd change the format to HHmm - zero-padding the value where appropriate - so "0919" would parse fine. Alternatively, use a colon in the format, to distinguish between the hours and the minutes. I don't believe there's any way of making DateTime parse a value of "919" as you want it to... so you'll need to adjust the string somehow before parsing it. (We don't have enough context to recommend a particular way of doing that.)
Yes, your format is right but since H specifier might be 2 character, ParseExact method try to parse 91 as an hour, which is an invalid hour, that's why you get FormatException in both case.
I connected to microsoft team about this situation 4 months ago. Take a look;
DateTime conversion from string C#
They suggest to use 2 digit form in your string or insert a date separator between them.
var time1 = DateTime.ParseExact("0919", "Hmm", CultureInfo.InvariantCulture);
or
var time1 = DateTime.ParseExact("9:19", "H:mm", CultureInfo.InvariantCulture);
You cant exclude the 0 prefix to the hour. This works
var time1 = DateTime.ParseExact("0919", "Hmm", CultureInfo.InvariantCulture);
Perhaps you want to just prefix 3-character times with a leading zero before parsing.
Much appreciated for all the answers. I don’t have control of the text being created so the simplest solution for me seemed to be prefixing a zero as opposed to adding a colon in the middle.
var text = "919";
var time = DateTime.ParseExact(text.PadLeft(4, '0'), "Hmm", null);

C# converting number into time error

I am reading time from a excel file and this is my code to convert number into time
string time = "1350";
DateTime dt = DateTime.ParseExact(time, "HHmm", CultureInfo.InvariantCulture);
string timestring = dt.ToString("h:mm tt");
Console.WriteLine(timestring);
Console.Read();
The problem is that my code works fine for 4 digit numbers but some numbers are like 600, 900 etc which should be converted into 6:00 PM and 9:00 PM but my code throws an error. Is there a better way to solve this?
Just pad them with zeros prior to converting to DateTime.
string time = "600".PadLeft(4, '0');
You're calling ParseExact which means the text has to exactly match the format string provided otherwise you get an error. The format string you are using: HHmm specifies a 24 hour time with leading zero for times earlier than noon. A string like "600" is only three characters long so it doesn't match the four character format (HHmm) specified.
It sounds like you don't want a leading zero so you probably want "hmm" (12 hour format) or "Hmm" (twenty-four hour format) so you can parse strings that don't have a leading zero. If you use Hmm you'll have to specify 6:00 pm as 1800. If you use hmm you'll probably also need to use the tt format string so you can distinguish 600 am from 600 pm
Try the below solution - yes ,i have tried this solution while importing data from excel
Double dateVal = Convert.ToDouble(mydatetime);
Date? dt = DateTime.FromOADate(dateVal);
string timestring = dt.ToString("h:mm tt");

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.

DateTime.ParseExact string format exception

I am trying to convert a string into datetime with the following C# code,
DateTime dTo = DateTime.ParseExact(dateTo, "mm/dd/yyyy", CultureInfo.InvariantCulture);
eachtime I pass dateTo as 1/1/2010 it fails, instead it needs the string to be 01/01/2010.
What string format should I use to support both 01/01/2010 and 1/1/2010?
Using the following date format expression will allow you to use either single or double digit day and month elements.
"M/d/yyyy"
Note that the capital M is significant - a lower case m is the placeholder for minutes.
You will find more information related to date format strings here.
You can use the following Powershell command to test them.
[DateTime]::ParseExact('01/01/2010', 'M/d/yyyy', $null)
Capital M is month, little m is mins i think.
But to the point of the question, use Parse. ParseExact implies you know the exact format of the input.
You could try this format: MM/dd/yyyy, but I think there's no single format string that could support both inputs. You could test if the length of your dateTo string is less than 10 characters use M/d/yyyy, otherwise MM/dd/yyyy.

Categories