0
点赞
收藏
分享

微信扫一扫

asp.net, c#,获取时间大全,时间运算,时间格式符号对照表

zmhc 2022-06-20 阅读 55

获取当天时间

DateTime.Now.Date.ToShortDateString();

获取当前时间的前一天 

DateTime.Now.AddDays(-1).ToShortDateString();

获取当前时间的上一小时

DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:ss");//上一小时

控制时间格式输出,如:2018-6-15

DateTime.Now.ToString("yyyy-MM-dd")

控制时间格式输出,如:2015-6-15 19:00:00

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")

获取系统时间及时间格式

DateTime 数字型 

System.DateTime currentTime=new System.DateTime();

取当前年月日时分秒      currentTime=System.DateTime.Now; 
取当前年     int 年=currentTime.Year; 
取当前月     int 月=currentTime.Month; 
取当前日     int 日=currentTime.Day; 
取当前时     int 时=currentTime.Hour; 
取当前分     int 分=currentTime.Minute; 
取当前秒     int 秒=currentTime.Second; 
取当前毫秒    int 毫秒=currentTime.Millisecond; (变量可用中文)

取中文日期显示——年月日时分    string strY=currentTime.ToString("f"); //不显示秒

取中文日期显示_年月       string strYM=currentTime.ToString("y");

取中文日期显示_月日     string strMD=currentTime.ToString("m");

取当前年月日,格式为:2003-9-23      string strYMD=currentTime.ToString("d");

取当前时分,格式为:14:24      string strT=currentTime.ToString("t");
 

DateTime.Now.ToString();//获取当前系统时间 完整的日期和时间
DateTime.Now.ToLongDateString();//只显示日期 xxxx年xx月xx日 ,一个是长日期
DateTime.Now.ToShortDateString();//只显示日期 xxxx-xx-xx 一个是短日期

今天       

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();

上周

上周就是本周再减去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();

下周   

本周再加上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();

本月

本月的第一天是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();//最后一天

另一种方法:

DateTime now = DateTime.Now; 

DateTime d1 = new DateTime(now.Year, now.Month, 1); //本月第一天

DateTime d2 = d1.AddMonths(1).AddDays(-1); //本月最后一天

PS:

DateTime.Now.DayOfWeek.ToString();//英文星期显示,Wednesday

(int)DateTime.Now.DayOfWeek     数字,若是周三,结果对应为3

DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("zh-cn")); //中文星期显示
DateTime.Now.ToString("dddd");//中文星期显示

DateTime.Now.ToString("dddd,MMMM,dd ,yyyy", new System.Globalization.DateTimeFormatInfo());//显示日期格式Friday,July, 01,2009

DateTime.Now.ToString("dddd,dd MMMM,yyyy") //输出   星期三,30 一月,2008

出处:http://msdn.microsoft.com/zh-cn/vstudio/bb762911(VS.95).aspx,如何:从特定日期中提取星期几

 

datetime类型在tostring()format的格式设置

参数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 

下表列出了可被合并以构造自定义模式的模式。这些模式是区分大小写的

    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 是任意字符。照原义显示字符。若要显示反斜杠字符,请使用“\\”。

只有上面第二个表中列出的格式模式才能用于创建自定义模式;在第一个表中列出的标准格式字符不能用于创建自定义模式。

自定义模式的长度至少为两个字符;例如,

1. DateTime.ToString( "d"); // 返回 DateTime 值;“d”是标准短日期模式。

2. DateTime.ToString( "%d"); // 返回月中的某天;“%d”是自定义模式。

3. DateTime.ToString( "d "); // 返回后面跟有一个空白字符的月中的某天;“d”是自定义模式。

常用日期处理函数

获取日期后比较2个日期的相差天数

static void DateTimeCheck()
{
string dateTime1 = "2021-07-18 11:58:44.053";
DateTime _dateTime1 ;
try
{
_dateTime1 = Convert.ToDateTime(dateTime1).Date;
DateTime _dateTime2 = DateTime.Now.Date;

TimeSpan span = _dateTime1.Subtract(_dateTime2);

int dayDiff = span.Days;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}


}

计算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;

计算某年某月的天数

int days = DateTime.DaysInMonth(2007, 8);
days = 31;

 给日期增加一天、减少一天

DateTime dt =DateTime.Now;
dt.AddDays(1); //增加一天
dt.AddDays(-1);//减少一天

*注:以下的毫秒都采用最大997,而不是999 因为SQL SERVER的精度为3毫秒

本月的天数

int daysInMonth = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);

本年的天数 是否是闰年   

int daysInYear = DateTime.IsLeapYear(DateTime.Now.Year) ? 366 : 365;

本月第一天

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

本月的最后一天 本月1号加一个月得下月1号,再剪掉一天就是本月最后一天

DateTime lastDayInMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1);

本月最后一天的午夜

DateTime lastDayInMonth2 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddMilliseconds(-3);

本年第一天

DateTime firstDayInYear = new DateTime(DateTime.Now.Year, 1, 1);

本年最后一天

DateTime lastDayInYear = new DateTime(DateTime.Now.Year, 12, 31);

本年最后一天的午夜

DateTime lastDayInYear2 = new DateTime(DateTime.Now.Year, 12, 31, 23, 59, 59, 997);

得到星期几 星期天为7

int dayOfWeek = Convert.ToInt32(DateTime.Now.DayOfWeek) < 1 ? 7 : Convert.ToInt32(DateTime.Now.DayOfWeek);

本周一

DateTime monday = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day).AddDays(1 - dayOfWeek);

本周 星期天

DateTime sunday = monday.AddDays(6);

本周 星期天的午夜

DateTime sunday2 = monday.AddDays(7).AddMilliseconds(-3);

本季度第一天

DateTime firsyDayInQuarter = new DateTime(DateTime.Now.Year, DateTime.Now.Month - (DateTime.Now.Month - 1) % 3, 1);

本季度最后一天

DateTime lastDayInQuarter = firsyDayInQuarter.AddMonths(3).AddDays(-1);

本季度最后一天的午夜

DateTime lastDayInQuarter2 = firsyDayInQuarter.AddMonths(3).AddMilliseconds(-3);
string datetime = "10-Jul-09";

string newdatetime = DateTime.Parse(datetime, new System.Globalization.CultureInfo("de-de")).ToString("yyyyMMdd");

符号对照表

.net版本:4.0

系统版本:Win7

符号

说明

语法

示例(2016-05-09 13:09:55:2350)

  yy

年份后两位

DateTime.Now.ToString("yy")

DateTime.Now.ToString("yy"); // => 16

  yyyy

4位年份

DateTime.Now.ToString("yyyy")

DateTime.Now.ToString("yyyy"); // => 2016

  MM

两位月份;单数月份前面用0填充

DateTime.Now.ToString("MM")

DateTime.Now.ToString("MM"); // => 05

  dd

日数

DateTime.Now.ToString("dd")

DateTime.Now.ToString("dd"); // => 09

  ddd

周几

DateTime.Now.ToString("ddd")

DateTime.Now.ToString("ddd"); // => 周一

  dddd

星期几

DateTime.Now.ToString("dddd")

DateTime.Now.ToString("dddd"); // => 星期一

  hh

12小时制的小时数

DateTime.Now.ToString("hh") 

DateTime.Now.ToString("hh"); // => 01

  HH

24小时制的小时数

DateTime.Now.ToString("HH")

DateTime.Now.ToString("HH"); // => 13

  mm

分钟数

DateTime.Now.ToString("mm")

DateTime.Now.ToString("mm"); // => 09

  ss

秒数

DateTime.Now.ToString("ss")

DateTime.Now.ToString("ss"); // => 55

  ff

毫秒数前2位

DateTime.Now.ToString("ff")

DateTime.Now.ToString("ff"); // => 23

  fff

毫秒数前3位

DateTime.Now.ToString("fff")

DateTime.Now.ToString("fff"); // => 235

  ffff

毫秒数前4位

DateTime.Now.ToString("ffff")

DateTime.Now.ToString("ffff"); // => 2350

  分隔符


可使用分隔符来分隔年月日时分秒。

包含的值可为:-、/、:等非关键字符



DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff"); // => 2016-05-09 13:09:55:2350

DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:ffff"); // => 2016/05/09 13:09:55:2350

DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:ffff dddd"); // => 2016/05/09 13:09:55:2350 星期一


asp.net, c#,获取时间大全,时间运算,时间格式符号对照表_自定义

C#比较两时间大小

比较时间大小的实验

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();

计算两个时间差值的函数,返回时间差的绝对值:

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;
}

实现计算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();

​​C# 错误日期格式转正确日期格式​​


private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
string newDate;
ConvertDate(textBox1.Text, out newDate);
textBox2.Text = newDate;
}
}

public bool ConvertDate(string strStart, out string newDate)
{
string longFormat = "yyyy-MM-dd HH:mm:ss", shortFormat = "yyyy-MM-dd";
newDate = strStart;
while (true)
{
if (newDate.IndexOf("//") >= 0)
newDate = newDate.Replace("//", "/");
else if (newDate.IndexOf(".") >= 0)
newDate = newDate.Replace(".", "/");
else if (newDate.IndexOf("。") >= 0)
newDate = newDate.Replace("。", "/");
else if (newDate.IndexOf("-") >= 0)
newDate = newDate.Replace("-", "/");
else if (newDate.IndexOf("、") >= 0)
newDate = newDate.Replace("、", "/");
else if (newDate.IndexOf("|") >= 0)
newDate = newDate.Replace("|", "/");
else if (newDate.IndexOf(":") >= 0)
newDate = newDate.Replace(":", ":");
else
break;
}
try
{
newDate = Convert.ToDateTime(newDate).ToString(longFormat);
return true;
}
catch
{
try
{
string[] str = newDate.Split(' ');
if (str.Count() > 0)
{
string[] sDate = str[0].Split('/');
if (sDate.Count() >= 3)
{
try
{
newDate = sDate[0] + "-" + sDate[1] + "-" + sDate[2];
if (str.Count() > 1)
{
newDate += " " + str[1];
newDate = Convert.ToDateTime(newDate).ToString(longFormat);
}
else
newDate = Convert.ToDateTime(newDate).ToString(shortFormat);
return true;
}
catch
{
newDate = sDate[2] + "-" + sDate[1] + "-" + sDate[0];
if (str.Count() > 1)
{
newDate += " " + str[1];
newDate = Convert.ToDateTime(newDate).ToString(longFormat);
}
else
newDate = Convert.ToDateTime(newDate).ToString(shortFormat);
return true;
}
}
}
}
catch
{
}
}

while (true)
{
if (strStart.IndexOf("//") >= 0)
strStart = strStart.Replace("//", "");
else if (strStart.IndexOf(".") >= 0)
strStart = strStart.Replace(".", "");
else if (strStart.IndexOf("。") >= 0)
strStart = strStart.Replace("。", "");
else if (strStart.IndexOf("-") >= 0)
strStart = strStart.Replace("-", "");
else if (strStart.IndexOf("、") >= 0)
strStart = strStart.Replace("、", "");
else if (strStart.IndexOf("|") >= 0)
strStart = strStart.Replace("|", "");
else if (strStart.IndexOf(":") >= 0)
strStart = strStart.Replace(":", "");
else if (strStart.IndexOf(":") >= 0)
strStart = strStart.Replace(":", "");
else
break;
}
try
{
//当strStart = "20121010" 这种类型
IFormatProvider ifp = new CultureInfo("zh-CN", true).DateTimeFormat;
DateTime dt = DateTime.ParseExact(strStart, "yyyyMMdd", ifp);
newDate = dt.ToString(shortFormat);
return true;
}
catch { }
try
{
//当strStart = "201210101230" 这种类型
IFormatProvider ifp = new CultureInfo("zh-CN", true).DateTimeFormat;
DateTime dt = DateTime.ParseExact(strStart, "yyyyMMddHHmm", ifp);
newDate = dt.ToString(longFormat);
return true;
}
catch { }
try
{
//当strStart = "20121010121320" 这种类型
IFormatProvider ifp = new CultureInfo("zh-CN", true).DateTimeFormat;
DateTime dt = DateTime.ParseExact(strStart, "yyyyMMddHHmmss", ifp);
newDate = dt.ToString(longFormat);
return true;
}
catch { }
try
{
//当strStart = "10102012" 这种类型
IFormatProvider ifp = new CultureInfo("zh-CN", true).DateTimeFormat;
DateTime dt = DateTime.ParseExact(strStart, "ddMMyyyy", ifp);
newDate = dt.ToString(shortFormat);
return true;
}
catch (Exception ex)
{
throw ex;
}
}


举报

相关推荐

0 条评论