格式日期在c# [英] format date in c#

查看:106
本文介绍了格式日期在c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将日期格式设置为 dd / mm / yyyy mm / dd / yy

How can I format a date as dd/mm/yyyy or mm/dd/yy ?

像VB中的格式(dd / mm / yy,现在)

如何在C#中执行此操作?

How can I do this in C#?

推荐答案

几乎相同,只需使用 DateTime.ToString()方法,例如:

It's almost the same, simply use the DateTime.ToString() method, e.g:

DateTime.Now.ToString("dd/MM/yy");

或:

DateTime dt = GetDate(); // GetDate() returns some date
dt.ToString("dd/MM/yy");

此外,您可能需要考虑使用预定义的日期/时间格式之一,例如: / p>

In addition, you might want to consider using one of the predefined date/time formats, e.g:

DateTime.Now.ToString("g");
// returns "02/01/2009 9:07 PM" for en-US
// or "01.02.2009 21:07" for de-CH 

这些确保格式正确,与当前的区域设置无关。

These ensure that the format will be correct, independent of the current locale settings.

查看以下MSDN页面了解更多信息

Check the following MSDN pages for more information

  • DateTime.ToString() method
  • Standard Date and Time Format Strings
  • Custom Date and Time Format Strings

一些额外的相关信息:

如果要显示在特定的区域/文化中的日期,然后存在 ToString()方法的重载,该方法需要一个 IFormatProvider

If you want to display a date in a specific locale / culture, then there is an overload of the ToString() method that takes an IFormatProvider:

DateTime dt = GetDate();
dt.ToString("g", new CultureInfo("en-US")); // returns "5/26/2009 10:39 PM"
dt.ToString("g", new CultureInfo("de-CH")); // returns "26.05.2009 22:39"

或者,您可以设置 CultureInfo 格式化日期之前的当前线程:

Or alternatively, you can set the CultureInfo of the current thread prior to formatting a date:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
dt.ToString("g"); // returns "5/26/2009 10:39 PM"

Thread.CurrentThread.CurrentCulture = new CultureInfo("de-CH");
dt.ToString("g"); // returns "26.05.2009 22:39"

这篇关于格式日期在c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆