开发者

DateTime parsing problem (DateTime.ParseExact)

开发者 https://www.devze.com 2023-01-30 17:41 出处:网络
[Please vote to close this - see my last comment.] Hi, Something like this: DateTime.ParseExact(\"25/12/2008 00:00:00\", \"dd/MM/yyyy HH:mm:ss\", CultureInfo.InvariantCulture);

[Please vote to close this - see my last comment.]

Hi,

Something like this:

DateTime.ParseExact("25/12/2008 00:00:00", "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

works fine on my development machine but not after deployment (server).

I guess it has to do with some time zone configuration. I have tried:

<%@ ... UICulture="en" Culture="en-US" %> 

with no avail. Any suggestions on a postcard please. Thanks.

Christian

PS: Exception:

String was not recognized as a valid DateTime

PPS: I have updated the question. I actually feed in the time bit. sorry about that!

PPPS: I have now realised that all this has to do with Excel and oledb. The string 25/12/2008 looks like this "12/25/2008 12:00:00 AM" on the server and like this "25/12/2008 00:开发者_运维百科00:00" on the developement machine. I adjusted the time zone of the server to UK without avail. What else can I do? Thank and sorry about all this confusion!!!


Something like this

You'd do better posting exactly what failed, and the exact error, rather than "something like" what failed.

I would expect your sample to give a FormatException, since the string you're converting ("25/12/2008", no time) does not match the format specified ("dd/MM/yyyy hh:mm:ss").

Also a bit strange to be using hh rather than HH in your format - hh is a 12-hour clock.

I would expect any of the following to work.

// No time component
DateTime.ParseExact("25/12/2008", "dd/MM/yyyy", new CultureInfo("en-US"));

// Works for hours <=12, result is always AM
DateTime.ParseExact("25/12/2008 11:00:00", "dd/MM/yyyy hh:mm:ss", new CultureInfo("en-US"));

// Works for hours using 24-hour clock
DateTime.ParseExact("25/12/2008 13:00:00", "dd/MM/yyyy HH:mm:ss", new CultureInfo("en-US"));


When parsing a string to DateTime, always consider that the date could have one or two digits for day and month. For example, it could be MM/dd/yyyy or M/d/yyyy or MM/d/yyyy or M/dd/yyyy. If you use ParseExact and you don't consider that, you'll get an exception. Try this:

DateTime date = DateTime.ParseExact(
    dateText, // date in string 
    new string[] { "M/d/yyyy", "MM/dd/yyyy", "M/dd/yyyy", "MM/d/yyyy" }, // formats (you can add more)
    CultureInfo.InvariantCulture, 
    DateTimeStyles.None);


try

DateTime.ParseExact("25/12/2008", "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
0

精彩评论

暂无评论...
验证码 换一张
取 消