如何更改 asp.net 中日期字符串的格式

how to change format of a date string in asp.net

我有一个日期字符串,例如“30/01/2018” 我想要像“2018/01/30”这样的格式

我试过以下几行,

DateTime.Parse(startDate.Text.ToString()).ToString("yyyy/MM/dd");

DateTime.ParseExact(startDate.Text.ToString(),"dd/MM/yyyy").ToString("yyyy/MM/dd");

但没用。 还有其他解决方案吗?

如果你想输出字符串。为什么不拆分并重新排列?

string strOldFormat = "30/01/2018";
string[] strArrOldFormat = strOldFormat.Split('/');
string strNewFormat = strArrOldFormat[2] + "/" + strArrOldFormat[1] + "/" + strArrOldFormat[0];

转义斜杠(并使用 ParseExact 的文化)

DateTime.ParseExact("30/01/2018","dd/MM/yyyy", CultureInfo.InvariantCulture)
    .ToString(@"yyyy\/MM\/dd")

或者使用 InvariantCulture 作为 ToString 而不是转义斜杠:

...ToString(@"yyyy/MM/dd", CultureInfo.InvariantCulture)

原因是,/ 是日期的特殊格式字符:

Custom Date and Time Format Strings - The "/" custom format specifier

The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture.

这样试试

string newFormat = DateTime.ParseExact("30/01/2018", "dd/MM/yyyy", CultureInfo.InvariantCulture)
    .ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);

你可以试试这个代码

string dateString = startDate.Text.ToString();
string format="yyyy/MM/dd"; 
string result;
CultureInfo provider = CultureInfo.InvariantCulture;
result = DateTimeOffset.ParseExact(dateString, format, provider).ToString();

或者你可以像这样把它捆绑成一行

string result = DateTimeOffset.ParseExact(startDate.Text.ToString(),"yyyy/MM/dd", CultureInfo.InvariantCulture).ToString();

更多信息here

尝试使用下面的示例代码:-

var  actualStartDate = DateTime.ParseExact(startDate.Text.ToString(),"yyyy/MM/dd", CultureInfo.InvariantCulture);

你可以用这个;

String.Format("{0: yyyy/MM/dd}", yourDate);