文章目录
- 1.将字符串转换为标准的DateTime格式
- 2.DateTime数据的相关应用
- 3.ParseExact的应用
- 4.TryParseExact的应用
1.将字符串转换为标准的DateTime格式
DateTime 格式是标准的格式,通过这个格式可以方便转换为其他格式、日期的增减、日期的比较等
using System.Diagnostics;
public class DateTime_Deom
{
public static void Main()
{
DateTime dt;
DateTime dtmin;
DateTime dtmax;
dt = Convert.ToDateTime("2015/01/22");
dtmin = dt.AddDays(-10);
dtmax = dt.AddMonths(2);
Console.WriteLine($"{dt}, {dtmin}, {dtmax}");
Debug.Assert(dtmin>=dt && dt<=dtmax, "Verify Wrong first !"); // 在output窗口输出结果:如果检验错误
Debug.Assert(dt >= dtmin && dt <= dtmax, "Verify Wrong second !");
Console.ReadKey();
}
}
// 2015 / 1 / 22 0:00:00, 2015 / 1 / 12 0:00:00, 2015 / 3 / 22 0:00:00
2.DateTime数据的相关应用
日期格式:yyyyMMdd HH:mm:ss(注意此字符串的字母大小写很严格)
yyyy:代表年份
MM: 代表月份
dd: 代表天
HH: 代表小时(24小时制)
mm: 代表分钟
ss: 代表秒
DateTime.Now.ToShortTimeString()
DateTime dt = DateTime.Now;
dt.ToString(); //2005-11-5 13:21:25
dt.ToFileTime().ToString(); //127756416859912816
dt.ToFileTimeUtc().ToString(); //127756704859912816
dt.ToLocalTime().ToString(); //2005-11-5 21:21:25
dt.ToLongDateString().ToString(); //2005年11月5日
dt.ToLongTimeString().ToString(); //13:21:25
dt.ToOADate().ToString(); //38661.5565508218
dt.ToShortDateString().ToString(); //2005-11-5
dt.ToShortTimeString().ToString(); //13:21
dt.ToUniversalTime().ToString(); //2005-11-5 5:21:25
dt.Year.ToString(); //2005
dt.Date.ToString(); //2005-11-5 0:00:00
dt.DayOfWeek.ToString(); //Saturday
dt.DayOfYear.ToString(); //309
dt.Hour.ToString(); //13
dt.Millisecond.ToString(); //441
dt.Minute.ToString(); //30
dt.Month.ToString(); //11
dt.Second.ToString(); //28
dt.Ticks.ToString(); //632667942284412864
dt.TimeOfDay.ToString(); //13:30:28.4412864
dt.ToString(); //2005-11-5 13:47:04
dt.AddYears(1).ToString(); //2006-11-5 13:47:04
dt.AddDays(1.1).ToString(); //2005-11-6 16:11:04
dt.AddHours(1.1).ToString(); //2005-11-5 14:53:04
dt.AddMilliseconds(1.1).ToString(); //2005-11-5 13:47:04
dt.AddMonths(1).ToString(); //2005-12-5 13:47:04
dt.AddSeconds(1.1).ToString(); //2005-11-5 13:47:05
dt.AddMinutes(1.1).ToString(); //2005-11-5 13:48:10
dt.AddTicks(1000).ToString(); //2005-11-5 13:47:04
dt.CompareTo(dt).ToString(); //0
dt.Add(?).ToString(); //问号为一个时间段
dt.Equals("2005-11-6 16:11:04").ToString(); //False
dt.Equals(dt).ToString(); //True
dt.GetHashCode().ToString(); //1474088234
dt.GetType().ToString(); //System.DateTime
dt.GetTypeCode().ToString(); //DateTime
dt.GetDateTimeFormats('s')[0].ToString(); //2005-11-05T14:06:25
dt.GetDateTimeFormats('t')[0].ToString(); //14:06
dt.GetDateTimeFormats('y')[0].ToString(); //2005年11月
dt.GetDateTimeFormats('D')[0].ToString(); //2005年11月5日
dt.GetDateTimeFormats('D')[1].ToString(); //2005 11 05
dt.GetDateTimeFormats('D')[2].ToString(); //星期六 2005 11 05
dt.GetDateTimeFormats('D')[3].ToString(); //星期六 2005年11月5日
dt.GetDateTimeFormats('M')[0].ToString(); //11月5日
dt.GetDateTimeFormats('f')[0].ToString(); //2005年11月5日 14:06
dt.GetDateTimeFormats('g')[0].ToString(); //2005-11-5 14:06
dt.GetDateTimeFormats('r')[0].ToString(); //Sat, 05 Nov 2005 14:06:25 GMT
string.Format("{0:d}",dt); //2005-11-5
string.Format("{0}",dt); //2005年11月5日
string.Format("{0:f}",dt); //2005年11月5日 14:23
string.Format("{0:F}",dt); //2005年11月5日 14:23:23
string.Format("{0:g}",dt); //2005-11-5 14:23
string.Format("{0:G}",dt); //2005-11-5 14:23:23
string.Format("{0:M}",dt); //11月5日
string.Format("{0:R}",dt); //Sat, 05 Nov 2005 14:23:23 GMT
string.Format("{0:s}",dt); //2005-11-05T14:23:23
string.Format("{0:t}",dt); //14:23
string.Format("{0:T}",dt); //14:23:23
string.Format("{0:u}",dt); //2005-11-05 14:23:23Z
string.Format("{0:U}",dt); //2005年11月5日 6:23:23
string.Format("{0:Y}",dt); //2005年11月
string.Format("{0}",dt); //2005-11-5 14:23:23
string.Format("{0:yyyyMMddHHmmssffff}",dt);
# 计算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); //减少一天
3.ParseExact的应用
// Summary:
// Converts the specified string representation of a date and time to its System.DateTime
// equivalent using the specified format and culture-specific format information.
// The format of the string representation must match the specified format exactly.
//
// Parameters:
// s:
// A string that contains a date and time to convert.
//
// format:
// A format specifier that defines the required format of s. For more information,
// see the Remarks section.
//
// provider:
// An object that supplies culture-specific format information about s.
//
// Returns:
// An object that is equivalent to the date and time contained in s, as specified
// by format and provider.
public static DateTime ParseExact(string s, string format, IFormatProvider? provider);
public class DateTime_Deom
{
public static void Main()
{
string str = "20120626";
IFormatProvider ifp = new CultureInfo("zh-CN", true);
DateTime dt = DateTime.ParseExact(str, "yyyyMMdd", ifp);
Console.WriteLine(dt.ToString("yyyy-M-dd"));
Console.ReadKey();
}
}
// 2012-6-26
ParseExact 这种方式解析时间格式,传递的时间字符串与时间format必须一致,否者代码中直接报错如下:
4.TryParseExact的应用
TryParseExact 避免了代码中直接报错的问题,不错是否能解析成功需要最终判断一下
# TryParseExact Summary
// Summary:
// Converts the specified string representation of a date and time to its System.DateTime
// equivalent using the specified format, culture-specific format information, and
// style. The format of the string representation must match the specified format
// exactly. The method returns a value that indicates whether the conversion succeeded.
//
// Parameters:
// s:
// A string containing a date and time to convert.
传递一个时间字符串格式,例如"25/3/2022" 或 "2022/3/25"
//
// format:
// The required format of s.
标准的日期格式"d/M/yyyy"
//
// provider:
// An object that supplies culture-specific formatting information about s.
//
// style:
// A bitwise combination of one or more enumeration values that indicate the permitted
// format of s.
//
// result:
// When this method returns, contains the System.DateTime value equivalent to the
// date and time contained in s, if the conversion succeeded, or System.DateTime.MinValue
// if the conversion failed. The conversion fails if either the s or format parameter
// is null, is an empty string, or does not contain a date and time that correspond
// to the pattern specified in format. This parameter is passed uninitialized.
//
// Returns:
// true if s was converted successfully; otherwise, false.
public static bool TryParseExact(string s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result)
{
DateTimeFormatInfo.ValidateStyles(style, "style");
return DateTimeParse.TryParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style, out result);
}
public class DateTime_Deom
{
public static void Main()
{
DateTime dt;
bool isValid = DateTime.TryParseExact("25/3/2022", "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal, out dt);
Console.WriteLine("----->{0}----->{1}", isValid, dt);
Console.ReadKey();
}
}
//----->True----->2022 / 3 / 25 0:00:00 // 解析正确的时候,dt正常传入时间格式
//----->False----->0001 / 1 / 1 0:00:00 // 解析错误的时候,dt输出标准时间