문제

I want to convert date to a specific format (e.g. en-US MM/dd/yyyy) and I am aware about normal method to parse it.

But in my case I'm unaware about the source date format. Source date format is subject to change as per server environment. It can be en-US or en-GB.

e.g. DateTime dt = DateTime.Now;

'dt' can be '27/03/2014' or '03/27/2014'.

How to convert the source date to en-US format if I don't know source date format?

(string format would be fine - MM/dd/yyyy e.g. "03/27/2014").

도움이 되었습니까?

해결책 2

DateTime.Now.toString("yyyy-MM-dd"); //toString(specify format)

try this one

다른 팁

If you don't know the source format, there is a chance of getting errors while trying to convert. For example, try converting:

05/01/2013

A computer wouldn't be able to identify the date in such a case. It could result in two outputs: 05 Jan, 2013 or 01 May, 2013.

DateTime result;
if (!DateTime.TryParseExact(inputString, "dd/MM/yyyy", out result)
    result = DateTime.ParseExact(inputString, "MM/dd/yyyy");

OR

DateTime result;
if (!DateTime.TryParse(inputString, out result)
    result = DateTime.ParseExact(inputString, CultureInfo.InvariantCulture, DateTimeStyles.None);

If you know your environment will always be the deciding factor, why not just use that?

Try some variation of the following:

string yourFormat = ... // Whatever is your default format

if(Thread.CurrentThread.CurrentCulture.Name == "en-US")
{
     yourFormat = "MM/dd/yyyy";
}
else (if Thread.CurrentThread.CurrentCulture.Name == "en-GB")
{
     yourFormat = "dd/MM/yyyy";
}

DateTime d = DateTime.ParseExact(inputString, yourFormat, null)

How to convert the source date to en-US format if I don't know source date format?

You need to know the source date format, only then can you convert it to the required date format.

As wiero has rightly said in the comments "If you have 01/02/2014 depending its 1 February or 2 January. You have to know how to read it".

The default format of the object returned by DateTime.Now will be the one specified in your server setting, check the screenshot below: enter image description here

enter image description here

Referring to @DarkWanderer's comment in question:

DateTime object has nothing to do with format.

Just needed to convert it to the specific format using ToString("MM/dd/yyyy").

I was using Parse() method to convert but it will not work. BToString() method is surely a way.

This will work: dt.Tostring("MM/dd/yyyy");

Thanks @DarkWanderer.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top