c datetime 格式化

c datetime 格式化

DateTime dt = DateTime.Now;
Label1.Text = dt.ToString();//2005-11-5 13:21:25
Label2.Text = dt.ToFileTime().ToString();//127756416859912816
Label3.Text = dt.ToFileTimeUtc().ToString();//127756704859912816
Label4.Text = dt.ToLocalTime().ToString();//2005-11-5 21:21:25
Label5.Text = dt.ToLongDateString().ToString();//2005年11月5日
Label6.Text = dt.ToLongTimeString().ToString();//13:21:25
Label7.Text = dt.ToOADate().ToString();//38661.5565508218
Label8.Text = dt.ToShortDateString().ToString();//2005-11-5
Label9.Text = dt.ToShortTimeString().ToString();//13:21
Label10.Text = dt.ToUniversalTime().ToString();//2005-11-5 5:21:25
?2005-11-5 13:30:28.4412864
Label1.Text = dt.Year.ToString();//2005
Label2.Text = dt.Date.ToString();//2005-11-5 0:00:00
Label3.Text = dt.DayOfWeek.ToString();//Saturday
Label4.Text = dt.DayOfYear.ToString();//309
Label5.Text = dt.Hour.ToString();//13
Label6.Text = dt.Millisecond.ToString();//441
Label7.Text = dt.Minute.ToString();//30
Label8.Text = dt.Month.ToString();//11
Label9.Text = dt.Second.ToString();//28
Label10.Text = dt.Ticks.ToString();//632667942284412864
Label11.Text = dt.TimeOfDay.ToString();//13:30:28.4412864
Label1.Text = dt.ToString();//2005-11-5 13:47:04
Label2.Text = dt.AddYears(1).ToString();//2006-11-5 13:47:04
Label3.Text = dt.AddDays(1.1).ToString();//2005-11-6 16:11:04
Label4.Text = dt.AddHours(1.1).ToString();//2005-11-5 14:53:04
Label5.Text = dt.AddMilliseconds(1.1).ToString();//2005-11-5 13:47:04
Label6.Text = dt.AddMonths(1).ToString();//2005-12-5 13:47:04
Label7.Text = dt.AddSeconds(1.1).ToString();//2005-11-5 13:47:05
Label8.Text = dt.AddMinutes(1.1).ToString();//2005-11-5 13:48:10
Label9.Text = dt.AddTicks(1000).ToString();//2005-11-5 13:47:04
Label10.Text = dt.CompareTo(dt).ToString();//0
//Label11.Text = dt.Add(?).ToString();//问号为一个时间段
Label1.Text = dt.Equals("2005-11-6 16:11:04").ToString();//False
Label2.Text = dt.Equals(dt).ToString();//True
Label3.Text = dt.GetHashCode().ToString();//1474088234
Label4.Text = dt.GetType().ToString();//System.DateTime
Label5.Text = dt.GetTypeCode().ToString();//DateTime

Label1.Text = dt.GetDateTimeFormats('s')[0].ToString();//2005-11-05T14:06:25
Label2.Text = dt.GetDateTimeFormats('t')[0].ToString();//14:06
Label3.Text = dt.GetDateTimeFormats('y')[0].ToString();//2005年11月
Label4.Text = dt.GetDateTimeFormats('D')[0].ToString();//2005年11月5日
Label5.Text = dt.GetDateTimeFormats('D')[1].ToString();//2005 11 05
Label6.Text = dt.GetDateTimeFormats('D')[2].ToString();//星期六 2005 11 05
Label7.Text = dt.GetDateTimeFormats('D')[3].ToString();//星期六 2005年11月5日
Label8.Text = dt.GetDateTimeFormats('M')[0].ToString();//11月5日
Label9.Text = dt.GetDateTimeFormats('f')[0].ToString();//2005年11月5日 14:06
Label10.Text = dt.GetDateTimeFormats('g')[0].ToString();//2005-11-5 14:06
Label11.Text = dt.GetDateTimeFormats('r')[0].ToString();//Sat, 05 Nov 2005 14:06:25 GMT

Label1.Text =? string.Format("{0:d}",dt);//2005-11-5
Label2.Text =? string.Format("{0:D}",dt);//2005年11月5日
Label3.Text =? string.Format("{0:f}",dt);//2005年11月5日 14:23
Label4.Text =? string.Format("{0:F}",dt);//2005年11月5日 14:23:23
Label5.Text =? string.Format("{0:g}",dt);//2005-11-5 14:23
Label6.Text =? string.Format("{0:G}",dt);//2005-11-5 14:23:23
Label7.Text =? string.Format("{0:M}",dt);//11月5日
Label8.Text =? string.Format("{0:R}",dt);//Sat, 05 Nov 2005 14:23:23 GMT
Label9.Text =? string.Format("{0:s}",dt);//2005-11-05T14:23:23
Label10.Text = string.Format("{0:t}",dt);//14:23
Label11.Text = string.Format("{0:T}",dt);//14:23:23
Label12.Text = string.Format("{0:u}",dt);//2005-11-05 14:23:23Z
Label13.Text = string.Format("{0:U}",dt);//2005年11月5日 6:23:23
Label14.Text = string.Format("{0:Y}",dt);//2005年11月
Label15.Text = string.Format("{0}",dt);//2005-11-5 14:23:23?
Label16.Text = string.Format("{0:yyyyMMddHHmmssffff}",dt); //yyyymm等可以设置,比如Label16.Text = string.Format("{0:yyyyMMdd}",dt);

Problem. You need help with DateTime formatting strings in C# or .NET languages. The framework provides powerful formatting capabilities, but the syntax is confusing and there are some tricks. Solution. Here we see examples of using DateTime formats, and also the different values you can get with the individual formats.

Format your DateTimes in the best way for your application. 
You will not have to write elaborate custom routines.       
The .NET Framework has a powerful DateTime format mechanism.

1. Using DateTime format string

Here we see an example of how you can use a specific formatting string with DateTime and ToString to obtain a special DateTime string. This is useful when interacting with other systems, or when you require a precise format.

=== Program that uses DateTime format (C#) ===

using System;

class Program
{
    static void Main()
    {
        DateTime time = DateTime.Now;              // Use current time
        string format = "MMM ddd d HH:mm yyyy";    // Use this format
        Console.WriteLine(time.ToString(format));  // Write to console
    }
}

=== Output of the program ===

Feb Fri 27 11:41 2009

=== Format string pattern ===

MMM     display three-letter month
ddd     display three-letter day of the WEEK
d       display day of the MONTH
HH      display two-digit hours on 24-hour scale
mm      display two-digit minutes
yyyy    display four-digit year

Notes on the letters. The letters in the format string above specify the output you want to display. The final comment shows what the MMM, ddd, d, HH, mm, and yyyy will do.

2. Modifying DateTime format string

Here we see how you can modify the DateTime format string in the above example to get different output with ToString. We change some of the fields so the resulting value is shorter.

=== Program that uses different format (C#) ===

using System;

class Program
{
    static void Main()
    {
        DateTime time = DateTime.Now;             // Use current time
        string format = "M d h:mm yy";            // Use this format
        Console.WriteLine(time.ToString(format)); // Write to console
    }
}

=== Output of the program ===

2 27 11:48 09

=== Format string pattern ===

M       display one-digit month number          [changed]
d       display one-digit day of the MONTH      [changed]
h       display one-digit hour on 12-hour scale [changed]
mm      display two-digit minutes
yy      display two-digit year                  [changed]

Note on format string usages. You will also need to specify a format string when using DateTime.ParseExact and DateTime.ParseExact. This is because those methods require a custom pattern to parse.

3. Single-letter DateTime format strings

Here we see that you can use a single character with ToString or DateTime.ParseExact to specify a preset format available in the framework. These are standard formats and very useful in many programs. They can eliminate typos in the custom format strings.

=== Program that tests formats (C#) ===

using System;

class Program
{
    static void Main()
    {
        DateTime now = DateTime.Now;
        Console.WriteLine(now.ToString("d"));
        Console.WriteLine(now.ToString("D"));
        Console.WriteLine(now.ToString("f"));
        Console.WriteLine(now.ToString("F"));
        Console.WriteLine(now.ToString("g"));
        Console.WriteLine(now.ToString("G"));
        Console.WriteLine(now.ToString("m"));
        Console.WriteLine(now.ToString("M"));
        Console.WriteLine(now.ToString("o"));
        Console.WriteLine(now.ToString("O"));
        Console.WriteLine(now.ToString("s"));
        Console.WriteLine(now.ToString("t"));
        Console.WriteLine(now.ToString("T"));
        Console.WriteLine(now.ToString("u"));
        Console.WriteLine(now.ToString("U"));
        Console.WriteLine(now.ToString("y"));
        Console.WriteLine(now.ToString("Y"));
    }
}

=== Output of the program ===

d    2/27/2009
D    Friday, February 27, 2009
f    Friday, February 27, 2009 12:11 PM
F    Friday, February 27, 2009 12:12:22 PM
g    2/27/2009 12:12 PM
G    2/27/2009 12:12:22 PM
m    February 27
M    February 27
o    2009-02-27T12:12:22.1020000-08:00
O    2009-02-27T12:12:22.1020000-08:00
s    2009-02-27T12:12:22
t    12:12 PM
T    12:12:22 PM
u    2009-02-27 12:12:22Z
U    Friday, February 27, 2009 8:12:22 PM
y    February, 2009
Y    February, 2009

4. ToLongDateString and ToShortDateString

Here we see the ToLongDateString, ToLongTimeString, ToShortDateString, and ToShortTimeString methods on DateTime. These methods are equivalent to the lowercase and uppercase D and T methods shown in the example above.

=== Program that uses ToString methods (C#) ===

using System;

class Program
{
    static void Main()
    {
        DateTime now = DateTime.Now;
        Console.WriteLine(now.ToLongDateString());  // Equivalent to D
        Console.WriteLine(now.ToLongTimeString());  // Equivalent to T
        Console.WriteLine(now.ToShortDateString()); // Equivalent to d
        Console.WriteLine(now.ToShortTimeString()); // Equivalent to t
        Console.WriteLine(now.ToString());
    }
}

=== Output of the program ===

ToLongDateString     Friday, February 27, 2009
ToLongTimeString     12:16:59 PM
ToShortDateString    2/27/2009
ToShortTimeString    12:16 PM
ToString             2/27/2009 12:16:59 PM

Note on default ToString method. The default ToString method on DateTime shown above is equivalent to the simple "G" formatting string in the previous example. In other words, ToString("G") and ToString() do the same thing.

5. Formatting characters

When you use DateTime.ParseExact, or ToString(), you need to specify a formatting string, which is a sequence of characters that designate how the final result will look. What follows are the author's notes on the strings from MSDN.

StringsNotes
dUse this to specify the numeric value for the day of the month.
It will be 1 or 2 digits long.
ddThis is the same as a single d, except there are always two digits, with a leading 0 prepended if necessary.
dddThis displays a three-letter string that indicates the current day of the week.
[See example after table]
ddddThis displays the full string for the day of the week.
[See example after table]
f
ff
fff
ffff
fffff
ffffff
fffffff
F
FF
FFF
FFFF
FFFFF
FFFFFF
FFFFFFF
Use the lowercase f to indicate the seconds to one digit length.
Use two lowercase fs to indicate the seconds to 2 digits.
Equivalent functionality for fff.
The uppercase F patterns do the same but work differently on trailing zeros.
ggUse this to display A.D. on your date.
It is unlikely that this will be B.C. in most programs.
[See example below table]
hDisplay the hours in one digit if possible.
If the hours is greater than 9, it will display two digits.
Range is 1-12.
hhDisplay the hours in two digits always, even if the hour is one digit.
The range here will be 01-12.
HThis represents the hours in a range of 0-23, which is called military time in some parts of the world. [See next row for two digits and link.]
HHThis represents the hours in a range of 00-23.
The only different here between the single H is that there is always a leading zero if the number is one digit. [C# 24-Hour and Military Time Methods - dotnetperls.com]
KUse this to display time zone information.
[Not shown]
m
mm
This formats the minutes in your date format string.
Here, the one m means that there is only one digit displayed if possible.
The two ms means that there are always two digits displayed, with a leading zero if necessary.
M
MM
These display the months in numeric form.
The one uppercase M does not have a leading zero on it.
The two uppercase Ms will format a number with a leading zero if it is required.
MMMThis displays the abbreviated three-letter form of the month represented in the DateTime.
[See example after table]
MMMMThis displays the full month string, properly capitalized.
[See example]
s
ss
The lowercase s displays seconds.
A single lowercase s means that you do not require a leading zero.
Two lowercase s characters means you always want two digits, such as 00-59.
tUse the lowercase t to indicate A, when the time is in the AM, and P, for when the time is in PM.
[See example]
ttUse two lowercase tts to display the full AM or PM string.
You will normally want this for when you are displaying the string to a user.
[See example after table]
y
yy
yyy
yyyy
yyyyy
These display the year to different digits.
In your programs, you won't need three digits for the year, or five.
Therefore, you should only consider 1 y, 2 ys, or 4 ys.
[See example]
z
zz
zzz
These represent the offset from the UTC time on the local operating system.
:This is the time separator.
/This is the date separator.
 Most other characters will be printed to the output string without any modification.

6. Difference between d and dd, ddd and dddd

It is important to note that d and dd (1 and 2 ds) mean something entirely different than ddd and dddd (3 and 4 ds). d and dd indicate the day of the MONTH, while ddd and dddd indicate the day of the WEEK, in a word. [See table above.]

7. Three-letter days

In some systems it may be useful to display the day of the week in a three-letter form. Here we see a simple program that prints out the days of the week in three-letter format. This will vary based on the language installed on the computer.

=== Program that tests days (C#) ===

using System;

class Program
{
    static void Main()
    {
        DateTime now = DateTime.Today;
        for (int i = 0; i < 7; i++)
        {
            Console.WriteLine(now.ToString("ddd"));
            now = now.AddDays(1);
        }
    }
}

=== Output of the program ===

Thu
Fri
Sat
Sun
Mon
Tue
Wed

8. Displaying complete day

Often you need to display the complete day of the week in C#, and the four ds together will do this for you. This simple program shows all seven different day strings you can get from the dddd.

=== Program that shows day strings (C#) ===

using System;

class Program
{
    static void Main()
    {
        DateTime now = DateTime.Today;
        for (int i = 0; i < 7; i++)
        {
            Console.WriteLine(now.ToString("dddd"));
            now = now.AddDays(1);
        }
    }
}

=== Output of the program ===

Thursday
Friday
Saturday
Sunday
Monday
Tuesday
Wednesday

9. Displaying the era

The .NET platform allows you to display the date with the era or period, which is usually A.D. or B.C. It is unlikely that you will need to use B.C., except in a rare theoretical application. Nevertheless, here is what the two gs will print. [Use the code |DateTime.Now.ToString("gg");|]

10. Month property and strings

You may need to display the month name in a three-letter format. This is equivalent, in English, to taking a substring of the first three letters, but using the 3 Ms next to each other may be easier and more terse for your code. Additionally, you may want full month strings. This site contains a useful article that covers DateTime month strings and the Month property in more detail. [C# DateTime.Month Property - dotnetperls.com]

11. Displaying AM/PM—first letter only

This isn't something you are likely to need, but interesting to find out. When you specify one t, you can get the first letter of the AM or PM string. This is equivalent to using Substring or getting the first char of the tt string. There is a space at the end of the format string because the value "t" can mean something else in the format string.

12. Displaying AM/PM—full string

Here we see how you can get the string AM or PM in your DateTime ToString code. The code adds 12 to ensure the second iteration is in the other half.

=== Program that displays AM and PM (C#) ===

using System;

class Program
{
    static void Main()
    {
        DateTime now = DateTime.Now;
        for (int i = 0; i < 2; i++)
        {
            Console.WriteLine(now.ToString("tt "));
            now = now.AddHours(12);
        }
    }
}

=== Output of the program ===

PM
AM

Note on lack of periods. There are no periods in the output of tt in the example above. Therefore, if you require periods in your AM or PM, you would have to manipulate the string.

13. Displaying year to different digits

You can vary the number of digits displayed in the year string. You will always want to use y, yy, or yyyy for your programs. The framework accepts different numbers, but they are impractical in the real world. Occasionally two ys is useful for a user-oriented program, but for your back end code, you will want to use four ys. You do not need uppercase Ys.

=== Program that displays years (C#) ===

using System;

class Program
{
    static void Main()
    {
        DateTime now = DateTime.Now;
        Console.WriteLine(now.ToString("y "));
        Console.WriteLine(now.ToString("yy"));
        Console.WriteLine(now.ToString("yyy"));   // <-- Don't use this
        Console.WriteLine(now.ToString("yyyy"));
        Console.WriteLine(now.ToString("yyyyy")); // <-- Don't use this
    }
}

=== Output of the program ===

9
09
2009
2009
02009

14. Summary

Here we saw lots of information and examples regarding DateTime format strings. We covered single-letter preset format strings, and more complicated custom format strings with different character codes. We saw an overview of the custom code letters. Finally, we saw enumerations of all the values for days of the week, months, and also three-letter versions of those. More general examples that use the format string system in the .NET Framework are available. [C# string.Format Method - dotnetperls.com] [Page protected by Copyscape. Do not copy.]


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值