C#日期时间格式化

来源:互联网 发布:网络漫画怎么画 编辑:程序博客网 时间:2024/04/28 01:06

 

C#日期格式化
from: http://51xingfu.blog.51cto.com/219185/46222

日期转化一

为了达到不同的显示效果有时,我们需要对时间进行转化,默认格式为:
2007-01-0314:33:34 ,要转化为其他格式,要用到DateTime.ToString的方法(String, IFormatProvider),如下所示:

using System;
using System.Globalization;
String format
="D";
DateTime date
=DataTime,Now;
Response.Write(date.ToString(format, DateTimeFormatInfo.InvariantInfo));

结果输出
Thursday, June
16, 2005

参数format格式详细用法:

格式字符 关联属性
/说明
d ShortDatePattern
D LongDatePattern
f 完整日期和时间(长日期和短时间)
F FullDateTimePattern(长日期和长时间)
g 常规(短日期和短时间)
G 常规(短日期和长时间)
m、M MonthDayPattern
r、R RFC1123Pattern
s 使用当地时间的 SortableDateTimePattern(基于 ISO
8601
t ShortTimePattern
T LongTimePattern
u UniversalSortableDateTimePattern 用于显示通用时间的格式
U 使用通用时间的完整日期和时间(长日期和长时间)
y、Y YearMonthPattern

下表列出了可被合并以构造自定义模式的模式。这些模式是区分大小写的;例如,识别“MM”,但不识别“mm”。如果自定义模式包含空白字符或用单引号括起来的字符,则输出字符串页也将包含这些字符。未定义为格式模式的一部分或未定义为格式字符的字符按其原义复制。

格式模式 说明
d 月中的某一天。一位数的日期没有前导零。
dd 月中的某一天。一位数的日期有一个前导零。
ddd 周中某天的缩写名称,在 AbbreviatedDayNames 中定义。
dddd 周中某天的完整名称,在 DayNames 中定义。
M 月份数字。一位数的月份没有前导零。
MM 月份数字。一位数的月份有一个前导零。
MMM 月份的缩写名称,在 AbbreviatedMonthNames 中定义。
MMMM 月份的完整名称,在 MonthNames 中定义。
y 不包含纪元的年份。如果不包含纪元的年份小于
10,则显示不具有前导零的年份。
yy 不包含纪元的年份。如果不包含纪元的年份小于
10,则显示具有前导零的年份。
yyyy 包括纪元的四位数的年份。
gg 时期或纪元。如果要设置格式的日期不具有关联的时期或纪元字符串,则忽略该模式。
h
12 小时制的小时。一位数的小时数没有前导零。
hh
12 小时制的小时。一位数的小时数有前导零。
H
24 小时制的小时。一位数的小时数没有前导零。
HH
24 小时制的小时。一位数的小时数有前导零。
m 分钟。一位数的分钟数没有前导零。
mm 分钟。一位数的分钟数有一个前导零。
s 秒。一位数的秒数没有前导零。
ss 秒。一位数的秒数有一个前导零。
f 秒的小数精度为一位。其余数字被截断。
ff 秒的小数精度为两位。其余数字被截断。
fff 秒的小数精度为三位。其余数字被截断。
ffff 秒的小数精度为四位。其余数字被截断。
fffff 秒的小数精度为五位。其余数字被截断。
ffffff 秒的小数精度为六位。其余数字被截断。
fffffff 秒的小数精度为七位。其余数字被截断。
t 在 AMDesignator 或 PMDesignator 中定义的 AM
/PM 指示项的第一个字符(如果存在)。
tt 在 AMDesignator 或 PMDesignator 中定义的 AM
/PM 指示项(如果存在)。
z 时区偏移量(“
+”或“-”后面仅跟小时)。一位数的小时数没有前导零。例如,太平洋标准时间是“-8”。
zz 时区偏移量(“
+”或“-”后面仅跟小时)。一位数的小时数有前导零。例如,太平洋标准时间是“-08”。
zzz 完整时区偏移量(“
+”或“-”后面跟有小时和分钟)。一位数的小时数和分钟数有前导零。例如,太平洋标准时间是“-08:00”。
: 在 TimeSeparator 中定义的默认时间分隔符。
/ 在 DateSeparator 中定义的默认日期分隔符。
% c 其中 c 是格式模式(如果单独使用)。如果格式模式与原义字符或其他格式模式合并,则可以省略“%”字符。
c 其中 c 是任意字符。照原义显示字符。若要显示反斜杠字符,请使用“/”。

只有上面第二个表中列出的格式模式才能用于创建自定义模式;在第一个表中列出的标准格式字符不能用于创建自定义模式。自定义模式的长度至少为两个字符;例如,

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

比较方便的是,上面的参数可以随意组合,并且不会出错,多试试,肯定会找到你要的时间格式
如要得到2005年06月 这样格式的时间
可以这样写:
date.ToString(
"yyyy年MM月", DateTimeFormatInfo.InvariantInfo)

日期转化二

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

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);
   Label17.Text = string.Format("{0:yyyyMMddHHmm}",dt);//200908171028

-----------------------------------------------------------------------------------------------------

//今天
DateTime.Now.Date.ToShortDateString();
//昨天,就是今天的日期减一
DateTime.Now.AddDays(-1).ToShortDateString();
//明天,同理,加一
DateTime.Now.AddDays(1).ToShortDateString();

//本周(要知道本周的第一天就得先知道今天是星期几,从而得知本周的第一天就是几天前的那一天,要注意的是这里的每一周是从周日始至周六止
DateTime.Now.AddDays(Convert.ToDouble((0 - Convert.ToInt16(DateTime.Now.DayOfWeek)))).ToShortDateString();
DateTime.Now.AddDays(Convert.ToDouble((6 - Convert.ToInt16(DateTime.Now.DayOfWeek)))).ToShortDateString();
//如果你还不明白,再看一下中文显示星期几的方法就应该懂了
//由于DayOfWeek返回的是数字的星期几,我们要把它转换成汉字方便我们阅读,有些人可能会用switch来一个一个地对照,其实不用那么麻烦的              
string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
Day[Convert.ToInt16(DateTime.Now.DayOfWeek)];

//上周,同理,一个周是7天,上周就是本周再减去7天,下周也是一样
DateTime.Now.AddDays(Convert.ToDouble((0 - Convert.ToInt16(DateTime.Now.DayOfWeek))) - 7).ToShortDateString();
DateTime.Now.AddDays(Convert.ToDouble((6 - Convert.ToInt16(DateTime.Now.DayOfWeek))) - 7).ToShortDateString();
//下周
DateTime.Now.AddDays(Convert.ToDouble((0 - Convert.ToInt16(DateTime.Now.DayOfWeek))) + 7).ToShortDateString();
DateTime.Now.AddDays(Convert.ToDouble((6 - Convert.ToInt16(DateTime.Now.DayOfWeek))) + 7).ToShortDateString();
//本月,很多人都会说本月的第一天嘛肯定是1号,最后一天就是下个月一号再减一天。当然这是对的
//一般的写法
DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + "1"; //第一天
DateTime.Parse(DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + "1").AddMonths(1).AddDays(-1).ToShortDateString();//最后一天

//巧用C#里ToString的字符格式化更简便
DateTime.Now.ToString("yyyy-MM-01");
DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(1).AddDays(-1).ToShortDateString();

//上个月,减去一个月份
DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(-1).ToShortDateString();
DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddDays(-1).ToShortDateString();
//下个月,加去一个月份
DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(1).ToShortDateString();
DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(2).AddDays(-1).ToShortDateString();
//7天后
DateTime.Now.Date.ToShortDateString();
DateTime.Now.AddDays(7).ToShortDateString();
//7天前
DateTime.Now.AddDays(-7).ToShortDateString();
DateTime.Now.Date.ToShortDateString();

//本年度,用ToString的字符格式化我们也很容易地算出本年度的第一天和最后一天
DateTime.Parse(DateTime.Now.ToString("yyyy-01-01")).ToShortDateString();
DateTime.Parse(DateTime.Now.ToString("yyyy-01-01")).AddYears(1).AddDays(-1).ToShortDateString();
//上年度,不用再解释了吧
DateTime.Parse(DateTime.Now.ToString("yyyy-01-01")).AddYears(-1).ToShortDateString();
DateTime.Parse(DateTime.Now.ToString("yyyy-01-01")).AddDays(-1).ToShortDateString();
//下年度
DateTime.Parse(DateTime.Now.ToString("yyyy-01-01")).AddYears(1).ToShortDateString();
DateTime.Parse(DateTime.Now.ToString("yyyy-01-01")).AddYears(2).AddDays(-1).ToShortDateString();

//本季度,很多人都会觉得这里难点,需要写个长长的过程来判断。其实不用的,我们都知道一年四个季度,一个季度三个月
//首先我们先把日期推到本季度第一个月,然后这个月的第一天就是本季度的第一天了
DateTime.Now.AddMonths(0 - ((DateTime.Now.Month - 1) % 3)).ToString("yyyy-MM-01");
//同理,本季度的最后一天就是下季度的第一天减一
DateTime.Parse(DateTime.Now.AddMonths(3 - ((DateTime.Now.Month - 1) % 3)).ToString("yyyy-MM-01")).AddDays(-1).ToShortDateString();
//下季度,相信你们都知道了。。。。收工
DateTime.Now.AddMonths(3 - ((DateTime.Now.Month - 1) % 3)).ToString("yyyy-MM-01");
DateTime.Parse(DateTime.Now.AddMonths(6 - ((DateTime.Now.Month - 1) % 3)).ToString("yyyy-MM-01")).AddDays(-1).ToShortDateString();
//上季度
DateTime.Now.AddMonths(-3 - ((DateTime.Now.Month - 1) % 3)).ToString("yyyy-MM-01");
DateTime.Parse(DateTime.Now.AddMonths(0 - ((DateTime.Now.Month - 1) % 3)).ToString("yyyy-MM-01")).AddDays(-1).ToShortDateString();

-----------------------------------------------------------------------------------------------------

C#取得某月的第一天,最后一天

取得某月的第一天
view plaincopy to clipboardprint?
  1. /// <summary>
  2. /// 取得某月的第一天
  3. /// </summary>
  4. /// <param name="datetime">要取得月份第一天的时间</param>
  5. /// <returns></returns>
  6. private DateTime FirstDayOfMonth(DateTime datetime)
  7. {
  8. return datetime.AddDays(1 - datetime.Day);
  9. }
  10. /**//// <summary>
  11. /// 取得某月的最后一天
  12. /// </summary>
  13. /// <param name="datetime">要取得月份最后一天的时间</param>
  14. /// <returns></returns>
  15. private DateTime LastDayOfMonth(DateTime datetime)
  16. {
  17. return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
  18. }
  19. /**//// <summary>
  20. /// 取得上个月第一天
  21. /// </summary>
  22. /// <param name="datetime">要取得上个月第一天的当前时间</param>
  23. /// <returns></returns>
  24. private DateTime FirstDayOfPreviousMonth(DateTime datetime)
  25. {
  26. return datetime.AddDays(1 - datetime.Day).AddMonths(-1);
  27. }
  28. /**//// <summary>
  29. /// 取得上个月的最后一天
  30. /// </summary>
  31. /// <param name="datetime">要取得上个月最后一天的当前时间</param>
  32. /// <returns></returns>
  33. private DateTime LastDayOfPrdviousMonth(DateTime datetime)
  34. {
  35. return datetime.AddDays(1 - datetime.Day).AddDays(-1);
  36. }
  37. http://www.cn-web.com/shtml/article/net/csharp/2009/02/04/366.shtml
    Net中获取一周第一天、最后一天,一月第一天、最后一天

DateTime dt = DateTime.Now;
        //本月第一天时间   
        DateTime dt_First = dt.AddDays(-(dt.Day) + 1);
        Label1.Text = dt_First.ToString("yyyy-MM-dd");
        //将本月月数+1 
        DateTime dt2 = dt.AddMonths(1);
        //本月最后一天时间 
        DateTime dt_Last = dt2.AddDays(-(dt.Day));
        Label2.Text = dt_Last.ToString("yyyy-MM-dd");
        int weeknow = Convert.ToInt32(System.DateTime.Now.DayOfWeek);
        int daydiff = (-1) * weeknow + 1;
        int dayadd = 7 - weeknow;

   //本周第一天
        lblBegin.Text = System.DateTime.Now.AddDays(daydiff).ToString("yyyy-MM-dd");

       //本周最后一天
        lblEnd.Text = System.DateTime.Now.AddDays(dayadd).ToString("yyyy-MM-dd");

DateTime now = DateTime.Now;
DateTime d1 = new DateTime(now.Year, now.Month, 1);

DateTime d2 = d1.AddMonths(1).AddDays(-1);

d1是本月的第一天,d2本月的最后一天,
最后一天的算法是:得到本月的第一天然后增加一月,再减去一天,

C#比较两时间大小

1、比较时间大小的实验    string st1="12:13";    string st2="14:14";    DateTime dt1=Convert.ToDateTime(st1);    DateTime dt2=Convert.ToDateTime(st2);    DateTime dt3=DateTime.Now;    if(DateTime.Compare(dt1,dt2)>0)     msg.Text=st1+">"+st2;    else     msg.Text=st1+"<"+st2;    msg.Text+="/r/n"+dt1.ToString();    if(DateTime.Compare(dt1,dt3)>0)     msg.Text+="/r/n"+st1+">"+dt3.ToString();    else     msg.Text+="/r/n"+st1+"<"+dt3.ToString();
2、计算两个时间差值的函数,返回时间差的绝对值:         private string DateDiff(DateTime DateTime1,DateTime DateTime2)         {             string dateDiff=null;             try             {                 TimeSpan ts1=new   TimeSpan(DateTime1.Ticks);                 TimeSpan ts2=new   TimeSpan(DateTime2.Ticks);                 TimeSpan ts=ts1.Subtract(ts2).Duration();                 dateDiff=ts.Days.ToString()+"天"                         +ts.Hours.ToString()+"小时"                         +ts.Minutes.ToString()+"分钟"                         +ts.Seconds.ToString()+"秒";             }             catch             {
             }             return dateDiff;         }
3、实现计算DateTime1-36天=DateTime2的功能
   TimeSpan ts=new TimeSpan(40,0,0,0);

    DateTime dt2=DateTime.Now.Subtract(ts);
    msg.Text=DateTime.Now.ToString()+"-"+ts.Days.ToString()+"天/r/n";
    msg.Text+=dt2.ToString();

4、执行一条SQL语句,查询两日期时间数据的操作

       

        QcTestDate为数据库表日期字段

        起始日期:dateTimeBegin,截止日期:dateTimeEnd

    ....where datediff(minute,cast(QcTestDate as datetime),'dateTimeBegin') <=0

        and datediff(minute,cast(QcTestDate as datetime),'dateTimeEnd') >=0

        查询给定日期一个月内的数据,起始日期:dateTimeBegin

    ....where datediff(minute,cast(QcTestDate as datetime),'dateTimeBegin') <=0

        and datediff(minute,cast(QcTestDate as datetime),

        dateadd(month,1,'dateTimeBegin')) >=0

    

4、对形式为"20091022"的string转换为"2009-10-22"的DateTime形式

        using System.Threading;

        DateTime Date = DateTime.ParseExact(receiveDateDatas[i], "yyyyMMdd", Thread.CurrentThread.CurrentCulture);

原创粉丝点击