示例一
using System; using System.Globalization; namespace DateTimeTest { class Program { static void Main(string[] args) { string timeStr; string timeFormat = "yyyy-MM-dd HH:mm:ss"; //格式化输出DateTime对象 timeStr = DateTime.Now.ToString(timeFormat); //字符串时间格式转DateTime DateTime dt = DateTime.ParseExact(timeStr, timeFormat, CultureInfo.CurrentCulture); Console.WriteLine("timeStr: {0}", timeStr); Console.WriteLine("dt: {0}", dt.ToString(timeFormat)); Console.Read(); } } }
using System;
/// <summary>
/// 关于白班与夜班时间判断
/// </summary>
public sealed class DayTimeDuty
{
// 是否在夜班时间段
public static bool IsNightShift()
{
return !IsDayShift();
}
// 是否在白班时间段 (8:00-20:00)
public static bool IsDayShift()
{
DateTime dt = DateTime.Now;
return (dt.Hour >= 8 && dt.Hour <= 19);
}
public static bool IsDayShift(DateTime dt)
{
return (dt.Hour >= 8 && dt.Hour <= 19);
}
// 是否在同班时间段
public static bool IsSameShift(DateTime dt)
{
DateTime cdt = DateTime.Now;
TimeSpan span = cdt - dt;
//相差12小时,肯定不在同一个班次
if (Math.Abs(span.TotalHours) >= 12)
return false;
return IsDayShift() == IsDayShift(dt);
}
// 是否在同班时间段
public static bool IsSameShift(DateTime dt1, DateTime dt2)
{
TimeSpan span = dt2 - dt1;
//相差12小时,肯定不在同一个班次
if (Math.Abs(span.TotalHours) >= 12)
return false;
return IsDayShift(dt1) == IsDayShift(dt2);
}
}