DateTime Problem

N

niju

Hi there
I am trying to get a single digit hour in 12-hour format with the
following code.

DateTime hr = DateTime.Now;
string hour = hr.ToString("h");

However, I get "Input string was not in a correct format" error. Please
help me to correct this problem.

Many Thanks
Niju
 
A

Andrea Zani

niju said:
Hi there
I am trying to get a single digit hour in 12-hour format with the
following code.

DateTime hr = DateTime.Now;
string hour = hr.ToString("h");

However, I get "Input string was not in a correct format" error.
Please help me to correct this problem.

string hout=hr.ToString("hh");
 
T

tom pester

Hi Niju,

How does the date that you are passing to the function? Maybe you have to
first use DateTime.Parse() to get it into a format the runtime understands
and than extract your desired format.


Let me know if it helped you or not...

Cheers,
Tom Pester
 
N

niju

Thanks Tom

I have no problem getting hour in 24-hour format with the
following code.

DateTime hr = DateTime.Now;
string hour = hr.ToString("hh");

However i cannot get a single digit hour in 12-hour format with the
following code.

DateTime hr = DateTime.Now;
string hour = hr.ToString("h");
 
T

tom pester

Hi niju,

I found the cause of the error :

"This is actually by design. A single character is interpreted as a Standard
DataTime format, "H" & "h"
are not standard DateTime format strings. Hence those two cause exceptions.
A Custom DateTime format needs to be at least 2 characters."

This extract is taken from http://groups.google.com/group/micr...g("h")+datetime&rnum=1&hl=en#24ea90ec4c52d91a

Try this code, it should work :

DateTime hr = new DateTime(2005,5,5,15,13,1);
string hour = hr.ToString("hh");
string hourTrimmed = hr.ToString("hh").TrimStart('0');

Response.Write(hour + "<br>" + hourTrimmed);

Let me know if it helped you or not...

Cheers,
Tom Pester
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top