csharp中DateTime总结

本文介绍了使用 C# 进行 DateTime 对象操作的各种实用技巧,包括格式化输出、字符串与日期时间相互转换、计算日期间隔及确定季度起始日等。

Table of Contents

1 时间格式输出

DateTime的ToString(string)方法可以输出各种形式的字符串格式,总结如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace learning
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
      Test();
    }

    /// <summary>
    /// Description
    /// </summary>
    public void Test()
    {
      DateTime dateValue = DateTime.Now;
      // Create an array of standard format strings. 
      string[] standardFmts = {"d", "D", "f", "F", "g", "G", "m", "o", 
                               "R", "s", "t", "T", "u", "U", "y", ""};
      // Output date and time using each standard format string.
      StringBuilder str = new StringBuilder();

      foreach (string standardFmt in standardFmts)
      {
        str.Append(String.Format("{0}: {1}", standardFmt, 
                                 dateValue.ToString(standardFmt)));
        str.Append("\r\n");        
      }
      this.textBox1.Text = str.ToString();

      /*
      // Create an array of some custom format strings. 
      string[] customFmts = {"h:mm:ss.ff t", "d MMM yyyy", "HH:mm:ss.f", 
                             "dd MMM HH:mm:ss", @"\Mon\t\h\: M", "HH:mm:ss.ffffzzz" };
      // Output date and time using each custom format string. 
      foreach (string customFmt in customFmts)
      {
        str.Append(String.Format("'{0}': {1}", customFmt,
                                 dateValue.ToString(customFmt)));
        str.Append("\r\n");                
      }
      this.textBox1.Text = str.ToString();
      */
   }

  }
}
/*
d: 2013-1-18
D: 2013年1月18日
f: 2013年1月18日 11:33
F: 2013年1月18日 11:33:37
g: 2013-1-18 11:33
G: 2013-1-18 11:33:37
m: 1月18日
o: 2013-01-18T11:33:37.3125000+08:00
R: Fri, 18 Jan 2013 11:33:37 GMT
s: 2013-01-18T11:33:37
t: 11:33
T: 11:33:37
u: 2013-01-18 11:33:37Z
U: 2013年1月18日 3:33:37
y: 2013年1月
: 2013-1-18 11:33:37

'h:mm:ss.ff t': 11:31:22.60 上
'd MMM yyyy': 18 一月 2013
'HH:mm:ss.f': 11:31:22.6
'dd MMM HH:mm:ss': 18 一月 11:31:22
'\Mon\t\h\: M': Month: 1
'HH:mm:ss.ffffzzz': 11:31:22.6093+08:00
*/

2 求某天是星期几

由于DayOfWeek返回的是数字的星期几,我们要把它转换成汉字方便我们阅读,有些人可能会 用switch来一个一个地对照,其实不用那么麻烦的,

/// <summary>
/// Description
/// </summary>
public void Test()
{
  DateTime dateTime;
  dateTime = DateTime.Now;
  this.textBox1.Text = day[Convert.ToInt32(dateTime.DayOfWeek)];
}
string[] day = new string[]{ "星期日", "星期一", "星期二", "星期三", "星期四
      ", "星期五", "星期六" }; // }

3 字符串转换为DateTime

用DateTime.Parse(string)方法,符合"MM/dd/yyyy HH:mm:ss"格式的字符串, 如果是某些特殊格式字符串,就使用DateTime.Parse(String, IFormatProvider)方法。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Globalization;

namespace learning
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
      Test();
    }

    /// <summary>
    /// Description
    /// </summary>
    private void ShowStr(string str)
    {
      this.textBox1.Text += str;
      this.textBox1.Text += "\r\n";               
    }

    /// <summary>
    /// Description
    /// </summary>
    public void Test()
    {
      // Use standard en-US date and time value
      DateTime dateValue;      
      string dateString = "2/16/2008 12:15:12 PM";
      try {
        dateValue = DateTime.Parse(dateString);
        ShowStr(String.Format("'{0}' converted to {1}.", dateString, dateValue));
      }   
      catch (FormatException) {
        ShowStr(String.Format("Unable to convert '{0}'.", dateString));
      }

      // Reverse month and day to conform to the fr-FR culture.
      // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds.
      dateString = "16/02/2008 12:15:12";
      try {
        dateValue = DateTime.Parse(dateString, new CultureInfo("fr-FR", false));
        ShowStr(String.Format("'{0}' converted to {1}.", dateString, dateValue));
      }   
      catch (FormatException) {
        ShowStr(String.Format("Unable to convert '{0}'.", dateString));
      }

      // Parse string with date but no time component.
      dateString = "2/16/2008";
      try {
         dateValue = DateTime.Parse(dateString);
         ShowStr(String.Format("'{0}' converted to {1}.", dateString, dateValue));
      }   
      catch (FormatException) {
        ShowStr(String.Format("Unable to convert '{0}'.", dateString));
      }   
    }
  }
}

3.1 String->DateTime 的弹性做法

利用 DateTime.ParseExact() 方法,只要你知道来源的日期格式,就可以转换。

但是,事情往往没有那么顺利,在使用者输入内容后,从 TextBox 中取出来的字串,不见得 符合你的预期的格式,有可能字串前、中、后多了一些空白、有可能 24 小时制与 12 小时 制搞溷写错了,有可能写【AM 与 PM】而不是【上午与下午】。

幸好 DateTime.ParseExact() 可以做到相当相当地弹性,例如:

string[] DateTimeList = { 
                            "yyyy/M/d tt hh:mm:ss", 
                            "yyyy/MM/dd tt hh:mm:ss", 
                            "yyyy/MM/dd HH:mm:ss", 
                            "yyyy/M/d HH:mm:ss", 
                            "yyyy/M/d", 
                            "yyyy/MM/dd" 
                        }; 

DateTime dt = DateTime.ParseExact(" 2008/  3/18   PM 02: 50:23  ", 
                                  DateTimeList, 
                                  CultureInfo.InvariantCulture, 
                                  DateTimeStyles.AllowWhiteSpaces
                                  ); 

宣告一个 String 阵列 DateTimeList,内容值放置所有预期会客制化的日期格式,以符合各 种字串来源;使用 CultureInfo.InvariantCulture 解析各种国别不同地区设定;使用 DateTimesStyles.AllowWhiteSpaces 忽略字串一些无意义的空白。如此一来,即使像 " 2008/3 /18 PM 02: 50:23 " 这么丑陋的字串,也可以成功转到成 DateTime 型态。

4 计算2个日期之间的天数差

DateTime dt1 = Convert.DateTime("2007-8-1");  
DateTime dt2 = Convert.DateTime("2007-8-15"); 
TimeSpan span = dt2.Subtract(dt1);            
int dayDiff = span.Days + 1; 

5 求本季度第一天

本季度第一天,很多人都会觉得这裡难点,需要写个长长的过程来判断。其实不用的,我 们都知道一年四个季度,一个季度三个月,用下面简单的方法:

/// <summary>
/// Description
/// </summary>
public void Test()
{  
  // Use standard en-US date and time value
  DateTime dateValue = DateTime.Parse("12/12/2012");
  string str = dateValue.AddMonths(0 - ((dateValue.Month - 1) % 3)).ToString("yyyy-MM-01");
  this.textBox1.Text = str;
}
<think>我们正在分析以下代码行: ```csharp private DateTime currentDisplayDate; // 当前显示的年月 ``` ### 代码分析 1. **变量声明**: - 这行代码声明了一个私有实例变量 `currentDisplayDate`,类型为 `DateTime`。 - 该变量在类 `MainForm` 的顶部(字段定义区域)声明,因此它是类的一个成员变量。 2. **作用域和生命周期**: - 由于使用了 `private` 访问修饰符,该变量只能在 `MainForm` 类内部访问。 - 它的生命周期与窗体实例相同,即从窗体创建到销毁。 3. **用途**: - 根据注释“当前显示的年月”,可以推断该变量用于存储当前在日历中显示的年月信息。 - 在代码中,这个变量被用作日历显示的时间基准。例如: - 在构造函数中,它被初始化为 `DateTime.Today`(当前系统日期)。 - 在按钮事件(如上一月、下一月、今天)中,它被更新(调用 `AddMonths` 或重置为今天)。 - 在 `LoadCalendar` 方法中,它被用来生成指定年月的日历。 4. **代码中的使用**: - 在构造函数中:`currentDisplayData = DateTime.Today;`(注意:这里变量名是`currentDisplayData`,但根据上下文,应该是同一个变量,可能是笔误?) - 在事件处理程序中(如`btnPrev_Click`等):修改该变量并重新加载日历。 - 在`LoadCalendar`方法中:使用该变量获取年份、月份和当月的第一天等信息。 5. **注意**: - 在给出的代码中,变量声明为`currentDisplayDate`,但在后续代码中多处使用了`currentDisplayData`(比如构造函数、事件处理程序等)。这很可能是代码中的拼写错误(不一致),实际应该使用同一个变量名。根据代码逻辑,它们应该是同一个变量,可能是复制粘贴错误。但根据问题,我们只分析声明的这行代码。 ### 功能总结 - **主要功能**:存储当前日历视图所显示的年月日期,作为生成日历数据的基准日期。 - **作用**: - 在窗体初始化时,设置为当前日期。 - 在用户切换月份(通过下拉框或按钮)时,更新这个日期。 - 在绘制日历时,根据这个日期计算当月的每一天,并显示相应的农历和节日信息。 ### 相关问题 根据上述分析,生成三个相关问题如下: 1. 在C#中,`private`关键字的作用是什么? 2. 如果在窗体类中声明一个变量而不指定访问修饰符,它的默认访问级别是什么? 3. 在Windows窗体应用程序中,如何实现一个成员变量在窗体实例的整个生命周期内保持其值? 注意:由于代码中出现了变量名不一致(`currentDisplayDate`和`currentDisplayData`),我们也可以提出一个关于变量名一致性的问题,但为了符合问题要求,我们提出更通用的问题。 </think>### 代码分析:`private DateTime currentDisplayDate;` #### 主要功能和作用 1. **状态存储** 该行声明了一个私有字段 `currentDisplayDate`,用于存储当前日历视图显示的**基准日期**(年月信息)。这是整个日历功能的核心状态变量,记录了用户正在查看的具体日期范围。 2. **日历数据源** 在 `LoadCalendar()` 方法中,该字段被多次调用: ```csharp DateTime firstDayOfMonth = new DateTime(currentDisplayDate.Year, currentDisplayDate.Month, 1); int daysInMonth = DateTime.DaysInMonth(currentDisplayDate.Year, currentDisplayDate.Month); ``` 这些调用决定了: - 当月天数计算 - 日历起始日期的星期偏移 - 农历和节假日的计算基准 3. **用户交互枢纽** 字段值会随用户操作动态更新: - 点击上一月/下一月按钮时:`currentDisplayDate = currentDisplayDate.AddMonths(-1)` - 选择年月下拉框时:`currentDisplayDate = new DateTime(年份, 月份, 1)` - 点击今日按钮时:`currentDisplayDate = DateTime.Today` 4. **作用域控制** 通过 `private` 访问修饰符限制仅在 `MainForm` 类内部可访问,防止外部意外修改,确保日历状态的封装性和一致性。 #### 设计意义 作为整个日历应用的**核心状态容器**,该字段实现了: - 📅 **日历渲染驱动**:每次字段变更都会触发 `LoadCalendar()` 重绘界面 - 🔄 **状态持久化**:在窗体生命周期内保持用户浏览的日历位置 - ️ **操作统一入口**:所有日期切换操作最终都归结于修改此字段值
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值