C# 将日期时间转换为指定格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9371658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:04:25  来源:igfitidea点击:

Convert DateTime to a specified Format

c#.netvb.netdatetime-format

提问by John Woo

I have this date format yy/MM/dd HH:mm:ssex: 12/02/21 10:56:09. The problem is, when i try to convert it to different format using this code:

我有这个日期格式, yy/MM/dd HH:mm:ss例如:12/02/21 10:56:09. 问题是,当我尝试使用以下代码将其转换为不同的格式时:

CDate("12/02/21 10:56:09").ToString("MMM. dd, yyyy HH:mm:ss")

It displays Dec. 12, 2021 10:56:09.

它显示Dec. 12, 2021 10:56:09.

How can i correctly format it to: Feb. 21, 2012 10:56:09? This format is returned when i check balance inquiry fro my SMS based application.

我怎样才能正确地将其格式化为:Feb. 21, 2012 10:56:09?当我从基于 SMS 的应用程序检查余额查询时返回此格式。

采纳答案by Kirill Polishchuk

Use DateTime.ParseExact, e.g.:

使用DateTime.ParseExact,例如:

DateTime.ParseExact("12/02/21 10:56:09", "yy/MM/dd HH:mm:ss", 
    CultureInfo.InvariantCulture
    ).ToString("MMM. dd, yyyy HH:mm:ss")

回答by siride

Assuming that you are meaning to ask how to get VB to parse the date as yy/MM/dd, the answer is simple: just use DateTime.ParseExact("12/02/12 10:56:09", "yy/MM/dd HH:mm:ss")and then use ToString()as before.

假设您想询问如何让 VB 将日期解析为 yy/MM/dd,答案很简单:只需使用DateTime.ParseExact("12/02/12 10:56:09", "yy/MM/dd HH:mm:ss")然后ToString()像以前一样使用。

回答by Dmitry Nogin

var dateTime = DateTime.ParseExact("12/02/21 10:56:09", "yy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture);

var text = dateTime.ToString("MMM. dd, yyyy HH:mm:ss");

回答by Pasha Immortals

Try this:

尝试这个:

DateTime.ParseExact("12/02/21 10:56:09", "yy/MM/dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture).ToString("MMM. dd, yyyy HH:mm:ss");

回答by Mitesh Vora

Even easier way to convert Date:

更简单的日期转换方法:

Convert.ToDateTime("12/02/21 10:56:09").ToString("MMM.dd,yyyy HH:mm:ss");