100% effective time formatting solution_C#

Format formatted output

string.Format();

project value
Format character Related attributes/description
d ShortDatePattern
D LongDatePattern
f Full date and time (long date and short time)
F FullDateTimePattern (long date and long time)
g Regular (short date and short time)
G Regular (short date and long time)
m、M MonthDayPattern
r、R RFC1123Pattern
s SortableDateTimePattern using local time (based on ISO 8601)
t ShortTimePattern
T LongTimePattern
u UniversalSortableDateTimePattern format used to display universal time
U Full date and time using universal time (long date and long time)
and 、 Y YearMonthPattern

example:

DateTime dt = DateTime.Now;
// 时间格式 yyyy/MM/dd
string time1 = string.Format("{0:d}",dt);
Console.WriteLine(time1);// 2020/10/31
// 时间格式 yyyy年MM月dd日
string time2 = string.Format("{0:D}",dt);
Console.WriteLine(time2);// 2020年10月31日

// 时间格式 yyyy年MM月
string time3 = string.Format("{0:Y}",dt);
Console.WriteLine(time4);// 2020年10月

// 时间格式 yyyy年MM月dd日 h:mm
string time4 = string.Format("{0:f}",dt);
Console.WriteLine(time4);// 2020年10月31日 9:15

// 时间格式 yyyy年MM月dd日 h:mm:ss
string time5 = string.Format("{0:F}",dt);
Console.WriteLine(time5);// 2020年10月31日 9:18:25

// 时间格式 MM月dd日
string time6 = string.Format("{0:M}",dt);
Console.WriteLine(time6);// 10月31日

// 时间格式 yyyy/MM/dd h:mm
string time7 = string.Format("{0:g}",dt);
Console.WriteLine(time7);// 2020/10/31 9:19

// 时间格式 yyyy/MM/dd h:mm:ss
string time8 = string.Format("{0:G}",dt);
Console.WriteLine(time8);// 2020/10/31 9:22:21

// 时间格式 mm:ss
string time9 = string.Format("{0:t}",dt);
Console.WriteLine(time9);// 9:25

// 时间格式 h:mm:ss
string time10 = string.Format("{0:T}",dt);
Console.WriteLine(time10);// 9:25:28

// 时间格式 yyyy-MM-dd h:mm:ss Z(中国)
string time11 = string.Format("{0:u}",dt);
Console.WriteLine(time11);// 2020-10-31 09:25:47Z

// 时间格式 yyyy年MM月dd日 h:mm:ss (通用)
string time12 = string.Format("{0:U}",dt);
Console.WriteLine(time12);// 2020年10月31日 1:26:01

string time13 = string.Format("{0:R}",dt);
Console.WriteLine(time13);// Sat, 31 Oct 2020 09:23:45 GMT

string time14 = string.Format("{0:s}",dt);
Console.WriteLine(time14);// 2020-10-31T09:24:21

string time15 = string.Format("{0}",dt);
Console.WriteLine(time15);// 2020/10/31 10:01:36

string time16 = string.Format("{0:yyyyMMddHHmmssffff}",dt); 
Console.WriteLine(time16);// 202010311002533500 

 The following table lists the modes that can be combined to construct custom modes. These patterns are case-sensitive; for example, "MM" is recognized but "mm" is not recognized . If the custom pattern contains blank characters or characters enclosed in single quotes, the output string page will also contain these characters. Characters that are not defined as part of the format pattern or format characters are copied in their original meaning

Format mode Description
d day of the month One-digit date without leading zero
dd day of the month One-digit dates have a leading zero
ddd Abbreviated name of day of week Defined in AbbreviatedDayNames
dddd the full name of the day of the week Defined in DayNames
M month number One-digit month without leading zero
MM month number One-digit month has a leading zero
Abbreviated name of MMM month Defined in AbbreviatedMonthNames
MMMM full name of the month Defined in MonthNames
y does not include the year of the era If the year without era is less than 10, the year without leading zero is displayed
yy does not include the year of the era If the year without the era is less than 10, the year with leading zeros is displayed
yyyy Four-digit year including era
gg period or era If the date to be formatted does not have an associated period or epoch string, then the pattern is ignored
h hour in 12-hour clock One-digit hour without leading zero
hh hour in 12-hour clock One-digit hours with leading zeros
H hour in 24-hour clock One-digit hour without leading zero
HH Hour in 24-hour clock One-digit hours with leading zeros
m minutes One-digit minutes without leading zero
mm minutes One-digit minutes have a leading zero
s seconds One-digit seconds without leading zero
ss seconds One-digit seconds have a leading zero
The decimal precision of f seconds is one digit The rest of the numbers are truncated
The decimal precision of ff seconds is two digits The rest of the numbers are truncated
The decimal precision of fff seconds is three digits The rest of the numbers are truncated
The decimal precision of ffff seconds is four digits The rest of the numbers are truncated
The decimal precision of fffff seconds is five digits The rest of the numbers are truncated
The decimal precision of ffffff seconds is six digits The rest of the numbers are truncated
The decimal precision of fffffff seconds is seven digits The rest of the numbers are truncated
t The first character of the AM/PM indicator defined in AMDesignator or PMDesignator (if it exists)
tt AM/PM indicator defined in AMDesignator or PMDesignator (if any)
z Time zone offset ("+" or "-" followed by hours only) One-digit hours have no leading zeros. For example, Pacific Standard Time is "-8"
zz time zone offset ("+" or "-" followed by hours only) One-digit hours have leading zeros. For example, Pacific Standard Time is "-08"
zzz full time zone offset ("+" or "-" followed by hours and minutes) One-digit hours and minutes have leading zeros. For example, Pacific Standard Time is "-08:00"
: The default time separator defined in TimeSeparator
/ The default date separator defined in DateSeparator
% c where c is the format mode (if used alone) If the format pattern is combined with literal characters or other format patterns, you can omit the "%" character
c where c is any character Display characters as they are. To display the backslash character, use "\"

 Only the format patterns listed in the second table above can be used to create custom patterns; the standard format characters listed in the first table cannot be used to create custom patterns. The length of the custom pattern is at least two characters; for example,

DateTime.ToString("d")返回 DateTime 值;“d”是标准短日期模式。
DateTime.ToString("%d")返回月中的某天;“%d”是自定义模式。
DateTime.ToString("d ") 返回后面跟有一个空白字符的月中的某天;“d”是自定义模式。

  • 比较方便的是,上面的参数可以随意组合,并且不会出错,多试试,肯定会找到你要的时间格式

C#日期转化

DateTime dt = DateTime.Now;
 dt.ToString();// 2020-10-31 10:10:25
 dt.ToFileTime().ToString();// 132485838882683121
 dt.ToFileTimeUtc().ToString();// 132485839117600286
 dt.ToLocalTime().ToString();// 2020/10/31 10:12:08
 dt.ToLongDateString().ToString();// 2020年10月31日
 dt.ToLongTimeString().ToString();// 10:13:10
 dt.ToOADate().ToString();// 44135.4260169097
 dt.ToShortDateString().ToString();// 2020/10/31
 dt.ToShortTimeString().ToString();// 10:14
 dt.ToUniversalTime().ToString();// 2020/10/31 2:14:19

 dt.Year.ToString();// 2020
 dt.Date.ToString();// 2020/10/31 0:00:00
 dt.DayOfWeek.ToString();// Saturday
 dt.DayOfYear.ToString();// 305
 dt.Hour.ToString();// 10
 dt.Millisecond.ToString();// 53
 dt.Minute.ToString();// 16
 dt.Month.ToString();// 10
 dt.Second.ToString();// 10
 dt.Ticks.ToString();// 637397362366997334
 dt.TimeOfDay.ToString();// 10:17:34.1632189

 dt.ToString();// 2020/10/31 10:17:52
 dt.AddYears(1).ToString();// 2021/10/31 10:18:09
 dt.AddDays(1.1).ToString();// 2020/11/1 12:42:26
 dt.AddHours(1.1).ToString();// 2020/10/31 11:24:43
 dt.AddMilliseconds(1.1).ToString();// 2020/10/31 10:19:30
 dt.AddMonths(1).ToString();// 2020/11/30 10:19:49
 dt.AddSeconds(1.1).ToString();// 2020/10/31 10:20:07
 dt.AddMinutes(1.1).ToString();// 2020/10/31 10:21:31
 dt.AddTicks(1000).ToString();// 2020/10/31 10:20:45
 dt.CompareTo(dt).ToString();// 0
 dt.Add(?).ToString();// 问号为一个时间段

 dt.Equals("2020-10-31 16:11:04").ToString();//False
 dt.Equals(dt).ToString();// True
 dt.GetHashCode().ToString();// -283369369
 dt.GetType().ToString();// System.DateTime
 dt.GetTypeCode().ToString();// DateTime


 dt.GetDateTimeFormats('s')[0].ToString();// 2020-10-31T10:23:45
 dt.GetDateTimeFormats('t')[0].ToString();// 10:24
 dt.GetDateTimeFormats('y')[0].ToString();// 2020年10月
 dt.GetDateTimeFormats('D')[0].ToString();// 2020年10月31日
 dt.GetDateTimeFormats('D')[1].ToString();// 2020年10月31日, 星期六
 
 dt.GetDateTimeFormats('D')[2].ToString();// 星期六, 2020年10月31日
 dt.GetDateTimeFormats('D')[3].ToString();// 2020年10月31日
 dt.GetDateTimeFormats('M')[0].ToString();// 10月31日
 dt.GetDateTimeFormats('f')[0].ToString();// 2020年10月31日 10:25
 dt.GetDateTimeFormats('g')[0].ToString();// 2020/10/31 10:26
 
 dt.GetDateTimeFormats('r')[0].ToString();// Sat, 31 Oct 2020 10:26:27 GMT

比较两个时间的大小

using System;

namespace dateTime
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            string st1 = "12:13";
            string st2 = "14:14";
            TimeRatioSize(st1, st2);
        }
        
		 /// <summary>
        /// 比较两个时间的大小
        /// </summary>
        /// <param name="st1"></param>
        /// <param name="st2"></param>
        public static void TimeRatioSize(string st1, string st2)
        {
    
    
            string msg;

            DateTime dt1 = Convert.ToDateTime(st1);
            DateTime dt2 = Convert.ToDateTime(st2);

            DateTime dt3 = DateTime.Now;

            if (DateTime.Compare(dt1, dt2) > 0)
                msg = st1 + ">" + st2;
            else
                msg = st1 + "<" + st2;
            msg += "\r\n" + dt1.ToString();

            if (DateTime.Compare(dt1, dt3) > 0)

                msg += "\r\n" + st1 + ">" + dt3.ToString();
            else
                msg += "\r\n" + st1 + "<" + dt3.ToString();
            Console.WriteLine(msg);
        }
    }
}

在这里插入图片描述

计算时间差

public static void DateDiff(DateTime T1, DateTime T2)
{
    
    
    string dateDiff;
    
    TimeSpan ts1 = new TimeSpan(T1.Ticks);
    TimeSpan ts2 = new TimeSpan(T2.Ticks);
    TimeSpan ts = ts1.Subtract(ts2).Duration();
    
    dateDiff = string.Format("{0}天{1}小时{2}分钟{3}秒",
        ts.Days.ToString(), ts.Hours.ToString(), ts.Minutes.ToString(), ts.Seconds.ToString());

    Console.WriteLine(dateDiff);
}

Guess you like

Origin blog.csdn.net/qq_43562262/article/details/109339657