如何将日期转换为mm / dd / yyyy格式

时间:2022-09-10 23:18:35

I want to convert dateformat to mm/dd/yyyy. Whatever dateformat is coming in textbox, I want to convert it into mm/dd/yyyy.

我想将dateformat转换为mm / dd / yyyy。无论日期格式是在文本框中,我想将其转换为mm / dd / yyyy。

2 个解决方案

#1


First you need to get it into a datetime object. The most common standards work via:

首先,您需要将其添加到日期时间对象中。最常见的标准是:

DateTime x = DateTime.Parse(txtDate.Text);

If you expect a freaky format, you still have to know what format it is:

如果你期望一种怪异的格式,你仍然需要知道它是什么格式:

DateTime x;
DateTime.TryParseExact(txtDate.Text, "YYddd", out x);

Then simply output the data:

然后只需输出数据:

string date = x.ToString("MM/dd/yyyy");

But you really need to enforce your formatting using regex, validators, scout's honor - something.

但是你真的需要使用正则表达式,验证器,侦察员的荣誉来强制执行格式化。

#2


see MSDN for full details.
You will need to parse the input to a DateTime object and then convert it to any text format you want.

有关详细信息,请参阅MSDN。您需要将输入解析为DateTime对象,然后将其转换为您想要的任何文本格式。

If you are unsure what format you may be getting, maybe it is a good idea to restrict the user to a single format (using validation or better yet a date picker).

如果您不确定您可能获得的格式,可能最好将用户限制为单一格式(使用验证或更好的日期选择器)。

#1


First you need to get it into a datetime object. The most common standards work via:

首先,您需要将其添加到日期时间对象中。最常见的标准是:

DateTime x = DateTime.Parse(txtDate.Text);

If you expect a freaky format, you still have to know what format it is:

如果你期望一种怪异的格式,你仍然需要知道它是什么格式:

DateTime x;
DateTime.TryParseExact(txtDate.Text, "YYddd", out x);

Then simply output the data:

然后只需输出数据:

string date = x.ToString("MM/dd/yyyy");

But you really need to enforce your formatting using regex, validators, scout's honor - something.

但是你真的需要使用正则表达式,验证器,侦察员的荣誉来强制执行格式化。

#2


see MSDN for full details.
You will need to parse the input to a DateTime object and then convert it to any text format you want.

有关详细信息,请参阅MSDN。您需要将输入解析为DateTime对象,然后将其转换为您想要的任何文本格式。

If you are unsure what format you may be getting, maybe it is a good idea to restrict the user to a single format (using validation or better yet a date picker).

如果您不确定您可能获得的格式,可能最好将用户限制为单一格式(使用验证或更好的日期选择器)。