C# converting number into time error - c#

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");

Related

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);

Issue regarding convert numeric value to 24 hrs format time

I was trying to convert a numeric value to 24 hours format time but the code is not working. Here is my code:
string xx =
Convert.ToDateTime(TimeSpan.FromHours(01).ToString())
.ToString("HH", System.Globalization.CultureInfo.InvariantCulture);
OR
string xx1 =
new DateTime(TimeSpan.FromHours(01).Ticks)
.ToString("HH", System.Globalization.CultureInfo.InvariantCulture);
OR
var t = DateTime.Now.TimeOfDay;
string xx2 =new DateTime(t.Ticks).ToString("hh:mm:ss tt");
OR
string ss = TimeSpan.FromHours(01).ToString("HH");
The above code is not working. I searched Google and everyone said use HH for getting hour in 24 hours format. Can anyone tell me if this is specific issue to my PC?
getting no error rather first line of code return 01 instead of 13.
Because you adding 1 hour from midnight. You should add 13 hour instead like;
string xx = Convert.ToDateTime(TimeSpan.FromHours(13).ToString())
.ToString("HH", System.Globalization.CultureInfo.InvariantCulture);
Since TimeSpan.FromHours(01).ToString() returns 01:00:00 as a string, Convert.ToDateTime parse this string as 13/01/2015 01:00:001.
And 24-hour clock representation of a 01 will be the same as itself no matter you use hh or HH specifier.
On your second example, you calculate your TimeSpan as a Ticks and DateTime(Int64) constructor calculates this time from 01/01/0001 and your DateTime evantually will be 01/01/0001 01:00:00 and still, it's 24-hour clock representation will be 01.
On your third example, you are calling DateTime(Int64) constructor with TimeOfDay property, that's why your DateTime will be 01.01.0001 15:10:36 (when I run your example right now) and it's hh:mm:ss tt representation will be 03:11:31 PM in InvariantCulture.
Your fourth line throws FormatException because there is no standard or custom HH format specifier of a TimeSpan.
1: Since you parse only hour without date, this method returns date part as a today

How to parse this string as a DateTime

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.

Convert string time like (0740) into 12 hours (AM,PM) time format like (07:40 AM)

How can i convert string time into 12 hours (AM,PM) time format?
Like if input string will like "2320" than i want answer like "11:20 PM".
string s = DateTime.ParseExact("2320","HHmm",CultureInfo.CurrentCulture)
.ToString("hh:mm tt");
I'm sure its been mentioned many times, but here is the reference for the to string parameters for Datetime here.
In Marc's answer, there is a leading zero in the hours if it is a single digit hour.
string s = DateTime.ParseExact("2320", "HHmm").ToString("h:mm tt");
The above would provide the format we're used to seeing from most digital clocks these days.

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