C# DateTime

获得当前系统时间: DateTime dt = DateTime.Now;

Environment.TickCount可以得到“系统启动到现在”的毫秒值

DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("yyyy-MM-dd"));  //按yyyy-MM-dd格式输出s

Console.WriteLine(dt.ToString());    //  26/11/2009 AM 11:21:30

Console.WriteLine(dt.ToFileTime().ToString());   //   129036792908014024

// Converts the value of the current System.DateTime object to a Windows file time

Console.WriteLine(dt.ToFileTimeUtc().ToString());  //     129036792908014024

// Converts the value of the current System.DateTime object to a Windows file time

Console.WriteLine(dt.ToLocalTime().ToString());   //       26/11/2009 AM 11:21:30

// Converts the value of the current System.DateTime object to local time.

Console.WriteLine(dt.ToLongDateString().ToString());   //      2009年11月26日

Console.WriteLine(dt.ToLongTimeString().ToString());  //      AM 11:21:30

Console.WriteLine(dt.ToOADate().ToString());   //      40143.4732731597

Console.WriteLine(dt.ToShortDateString().ToString());   //     26/11/2009

Console.WriteLine(dt.ToShortTimeString().ToString());   //     AM 11:21

Console.WriteLine(dt.ToUniversalTime().ToString());   //       26/11/2009 AM 3:21:30

Console.WriteLine(dt.Year.ToString());   //        2009

Console.WriteLine(dt.Date.ToString());   //        26/11/2009 AM 12:00:00

Console.WriteLine(dt.DayOfWeek.ToString());  //       Thursday

Console.WriteLine(dt.DayOfYear.ToString());   //       330

Console.WriteLine(dt.Hour.ToString());       //        11

Console.WriteLine(dt.Millisecond.ToString());   //     801        (毫秒)

Console.WriteLine(dt.Minute.ToString());   //      21

Console.WriteLine(dt.Month.ToString());   //       11

Console.WriteLine(dt.Second.ToString());   //      30

Console.WriteLine(dt.Ticks.ToString());   //       633948312908014024


Console.WriteLine(dt.TimeOfDay.ToString());   //       12:29:51.5181524

// Gets the time of day for this instance.

// 返回 A System.TimeSpan that represents the fraction of the day that has elapsed since midnight.

Console.WriteLine(dt.ToString());     //     26/11/2009 PM 12:29:51

Console.WriteLine(dt.AddYears(1).ToString());    //         26/11/2010 PM 12:29:51

Console.WriteLine(dt.AddDays(1.1).ToString());    //        27/11/2009 PM 2:53:51

Console.WriteLine(dt.AddHours(1.1).ToString());    //       26/11/2009 PM 1:35:51

Console.WriteLine(dt.AddMilliseconds(1.1).ToString());    //26/11/2009 PM 12:29:51

Console.WriteLine(dt.AddMonths(1).ToString());    //        26/12/2009 PM 12:29:51

Console.WriteLine(dt.AddSeconds(1.1).ToString());    //     26/11/2009 PM 12:29:52

Console.WriteLine(dt.AddMinutes(1.1).ToString());    //     26/11/2009 PM 12:30:57

Console.WriteLine(dt.AddTicks(1000).ToString());    //      26/11/2009 PM 12:29:51

Console.WriteLine(dt.CompareTo(dt).ToString());    //       0

Console.WriteLine(dt.Add(new TimeSpan(1,0,0,0)).ToString());    // 加上一个时间段

(注:

System.TimeSpan为一个时间段,构造函数如下

public TimeSpan(long ticks); // ticks: A time period expressed in 100-nanosecond units.

                           //nanosecond:十亿分之一秒   new TimeSpan(10,000,000)        为一秒

public TimeSpan(int hours, int minutes, int seconds);

public TimeSpan(int days, int hours, int minutes, int seconds);

public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds);

Console.WriteLine(dt.Equals("2005-11-6 16:11:04").ToString());     //        False

Console.WriteLine(dt.Equals(dt).ToString());    //      True

Console.WriteLine(dt.GetHashCode().ToString());    //       1103291775

Console.WriteLine(dt.GetType().ToString());    //       System.DateTime

Console.WriteLine(dt.GetTypeCode().ToString());    //       DateTime
  

long Start = Environment.TickCount;   //单位是毫秒

long End = Environment.TickCount;

Console.WriteLine("Start is : "+Start);

Console.WriteLine("End is : "+End);

Console.WriteLine("The Time is {0}",End-Start);
Console.WriteLine(dt.GetDateTimeFormats('s')[0].ToString());    //2009-11-26T13:29:06

Console.WriteLine(dt.GetDateTimeFormats('t')[0].ToString());    //PM 1:29

Console.WriteLine(dt.GetDateTimeFormats('y')[0].ToString());    //2009年11月

Console.WriteLine(dt.GetDateTimeFormats('D')[0].ToString());    //2009年11月26日

Console.WriteLine(dt.GetDateTimeFormats('D')[1].ToString());    //星期四, 26 十一月, 2009

Console.WriteLine(dt.GetDateTimeFormats('D')[2].ToString());    //26 十一月, 2009

Console.WriteLine(dt.GetDateTimeFormats('D')[3].ToString());    //星期四 2009 11 26

Console.WriteLine(dt.GetDateTimeFormats('M')[0].ToString());    //26 十一月

Console.WriteLine(dt.GetDateTimeFormats('f')[0].ToString());    //2009年11月26日 PM 1:29

Console.WriteLine(dt.GetDateTimeFormats('g')[0].ToString());    //26/11/2009 PM 1:29

Console.WriteLine(dt.GetDateTimeFormats('r')[0].ToString());    //Thu, 26 Nov 2009 13:29:06 GMT

(注:

常用的日期时间格式:

格式 说明      输出格式 
d 精简日期格式 MM/dd/yyyy 
D 详细日期格式 dddd, MMMM dd, yyyy 
f  完整格式    (long date + short time) dddd, MMMM dd, yyyy HH:mm 
F 完整日期时间格式 (long date + long time) dddd, MMMM dd, yyyy HH:mm:ss 
g 一般格式 (short date + short time) MM/dd/yyyy HH:mm 
G 一般格式 (short date + long time) MM/dd/yyyy HH:mm:ss 
m,M 月日格式 MMMM dd 
s 适中日期时间格式 yyyy-MM-dd HH:mm:ss 
t 精简时间格式 HH:mm 
T 详细时间格式 HH:mm:ss

)


Console.WriteLine(string.Format("{0:d}", dt));    //28/12/2009

Console.WriteLine(string.Format("{0:D}", dt));    //2009年12月28日

Console.WriteLine(string.Format("{0:f}", dt));    //2009年12月28日 AM 10:29

Console.WriteLine(string.Format("{0:F}", dt));    //2009年12月28日 AM 10:29:18

Console.WriteLine(string.Format("{0:g}", dt));    //28/12/2009 AM 10:29

Console.WriteLine(string.Format("{0:G}", dt));    //28/12/2009 AM 10:29:18

Console.WriteLine(string.Format("{0:M}", dt));    //28 十二月

Console.WriteLine(string.Format("{0:R}", dt));    //Mon, 28 Dec 2009 10:29:18 GMT

Console.WriteLine(string.Format("{0:s}", dt));    //2009-12-28T10:29:18

Console.WriteLine(string.Format("{0:t}", dt));    //AM 10:29

Console.WriteLine(string.Format("{0:T}", dt));    //AM 10:29:18

Console.WriteLine(string.Format("{0:u}", dt));    //2009-12-28 10:29:18Z

Console.WriteLine(string.Format("{0:U}", dt));    //2009年12月28日 AM 2:29:18

Console.WriteLine(string.Format("{0:Y}", dt));    //2009年12月

Console.WriteLine(string.Format("{0}", dt));    //28/12/2009 AM 10:29:18

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

计算2个日期之间的天数差
DateTime dt1 = Convert.ToDateTime("2007-8-1");    
DateTime dt2 = Convert.ToDateTime("2007-8-15");   
TimeSpan span = dt2.Subtract(dt1);              
int dayDiff = span.Days ;                    

计算某年某月的天数
int days = DateTime.DaysInMonth(2009, 8);       
days = 31;                                      

给日期增加一天、减少一天
DateTime dt =DateTime.Now;
dt.AddDays(1); //增加一天 dt本身并不改变
dt.AddDays(-1);//减少一天 dt本身并不改变

<think> 首先,用户的问题是关于C#DateTime的使用方法和示例。我需要基于提供的引用和系统指令来构建回答。 系统指令要求: - 所有行内数学表达式使用$...$格式。但在这个上下文中,可能没有数学表达式,所以可能不需要。 - 独立公式使用$$...$$格式并单独成段。同样,可能不适用。 - LaTeX语法正确。 - 使用中文回答。 - 生成相关问题。 - 回答中引用的段落末尾自然地添加引用标识,例如[^1]。 - 回答结构清晰,帮助用户逐步解决问题,尽量保证回答真实可靠。 用户提供了一些引用: - [^1]:关于DateTime.CompareTo方法的详解及示例。 - [^2]:关于C#DateTime的用法,包括格式化和常规计算。 - [^3]:关于DateTime类型转换,特别是string到DateTime的转换。 - [^4]:关于DateTime的常用方法,如Add。 用户的问题是:“我想查找关于C#DateTime的相关信息,可能是使用方法、示例、特性等 请问C#DateTime的使用方法和示例”。所以,我需要覆盖DateTime的基本使用方法、示例、特性等。 结构化回答: 1. **介绍DateTime**:简要解释DateTime是什么。 2. **基本用法**:包括创建DateTime对象、常用属性、方法等。 3. **示例代码**:提供一些简单的代码示例来演示用法。 4. **引用相关部分**:在回答中自然地添加引用标识。 5. **生成相关问题**:在结尾添加相关问题。 确保回答真实可靠,基于提供的引用和一般知识。 关键点从引用中提取: - 从[^1]:DateTime.CompareTo方法用于比较两个DateTime对象,返回整数表示关系。 - 从[^2]:DateTime包含日期和时间,可以通过ToString()方法转换为不同格式的字符串。 - 从[^3]:string到DateTime的转换,可以使用Convert.ToDateTime或指定格式。 - 从[^4]:Add方法用于添加TimeSpan到DateTime。 我还可以添加其他常见用法,如获取当前时间、操作日期等,以丰富回答。 最终结构: - 开头介绍DateTime。 - 分节讨论: - 创建DateTime对象。 - 常用属性和方法(包括引用中的Add和CompareTo)。 - 格式化(ToString)。 - 类型转换(string到DateTime)。 - 提供代码示例。 - 结尾添加相关问题。 使用中文回答。 生成相关问题: - 基于主题,生成3-5个相关问题。 </think> ### C#DateTime的使用方法和示例 DateTimeC#中用于表示日期和时间的关键类型,它位于System命名空间下。它提供了丰富的功能来处理日期、时间、时区等操作。下面我将分步介绍DateTime的核心使用方法、特性,并提供示例代码,帮助你快速掌握。所有示例基于.NET框架,确保真实可靠。 #### 1. **创建和初始化DateTime对象** - DateTime对象可以通过构造函数创建,支持指定年、月、日、时、分、秒等参数。 - 常用属性: - `Now`:获取当前系统时间。 - `Today`:获取当前日期(时间部分为00:00:00)。 - `Year`、`Month`、`Day`等:访问日期组件。 - 示例代码: ```csharp // 创建特定日期时间 DateTime date1 = new DateTime(2023, 10, 15); // 2023年10月15日 DateTime date2 = new DateTime(2023, 10, 15, 14, 30, 0); // 2023年10月15日14:30:00 // 获取当前时间 DateTime currentTime = DateTime.Now; Console.WriteLine($"当前时间: {currentTime}"); // 访问属性 int year = currentTime.Year; // 例如返回2023 Console.WriteLine($"年份: {year}"); ``` #### 2. **常用方法** - **Add方法**:用于添加时间间隔(如天、小时、分钟),返回新的DateTime对象。例如,添加一天或一周[^4]。 - 示例: ```csharp DateTime now = DateTime.Now; DateTime tomorrow = now.AddDays(1); // 添加一天 Console.WriteLine($"明天: {tomorrow}"); DateTime nextWeek = now.Add(TimeSpan.FromDays(7)); // 添加一周 Console.WriteLine($"下周: {nextWeek}"); ``` - **CompareTo方法**:比较两个DateTime对象,返回整数(小于0表示前一个日期早于后一个,等于0表示相等,大于0表示晚于)。这在排序或条件判断中常用[^1]。 - 示例: ```csharp DateTime dateA = new DateTime(2023, 1, 1); DateTime dateB = new DateTime(2023, 1, 2); int result = dateA.CompareTo(dateB); // 返回-1(因为dateA早于dateB) Console.WriteLine($"比较结果: {result}"); // 输出: -1 ``` - **其他方法**: - `AddDays()`、`AddHours()`等:快捷方法添加特定单位时间。 - `Subtract()`:计算两个DateTime之间的时间差,返回TimeSpan对象。 - 示例: ```csharp // 计算日期差 TimeSpan difference = dateB.Subtract(dateA); // 返回1天的TimeSpan Console.WriteLine($"日期差: {difference.TotalDays} 天"); // 输出: 1 ``` #### 3. **格式化和转换** - **ToString格式化**:DateTime对象可以通过ToString()方法转换为自定义格式的字符串。使用格式字符串控制输出,如"yyyy-MM-dd"或"hh:mm:ss"[^2]。 - 示例: ```csharp DateTime date = new DateTime(2023, 10, 15, 14, 30, 0); string formattedDate = date.ToString("yyyy-MM-dd"); // 输出: "2023-10-15" string formattedTime = date.ToString("HH:mm:ss"); // 输出: "14:30:00" Console.WriteLine($"格式化日期: {formattedDate}"); ``` - **字符串到DateTime转换**:可以使用Convert.ToDateTimeDateTime.Parse方法。注意格式必须匹配,否则会抛出异常。指定格式时,可使用DateTimeFormatInfo对象[^3]。 - 示例: ```csharp // 方法1: 使用Convert.ToDateTime (要求字符串格式为标准) string dateString = "2023-10-15"; DateTime parsedDate1 = Convert.ToDateTime(dateString); // 方法2: 指定自定义格式 System.Globalization.DateTimeFormatInfo formatInfo = new System.Globalization.DateTimeFormatInfo(); formatInfo.ShortDatePattern = "yyyy/MM/dd"; DateTime parsedDate2 = Convert.ToDateTime("2023/10/15", formatInfo); Console.WriteLine($"解析后的日期: {parsedDate2}"); ``` #### 4. **特性与注意事项** - **不变性**:DateTime类型,所有方法(如Add)都返回新对象,原始对象不变。 - **时区处理**:默认使用系统时区。对于复杂时区场景,建议使用DateTimeOffset或TimeZoneInfo类。 - **性能**:DateTime操作高效,适合频繁计算(如日志记录或调度系统)。 - 示例:结合多个操作 ```csharp // 创建日期,添加时间,并格式化 DateTime startDate = new DateTime(2023, 1, 1); DateTime endDate = startDate.AddMonths(3).AddDays(5); // 添加3个月和5天 string output = endDate.ToString("MMMM dd, yyyy"); // 输出格式如 "April 06, 2023" Console.WriteLine($"最终日期: {output}"); ``` 以上方法覆盖了DateTime的核心用法。实际开发中,结合异常处理(如使用DateTime.TryParse解析字符串)以避免错误[^3]。如果你有特定场景(如数据库操作),可以提供更多细节,我可以深入解释。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值