公共类 DAtaTimeHelper类的编写

public class Appointment
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
public static class DateTimeExtensions
{
public static DateTime FromTodayGetSundayDay(this DateTime day)
{
switch (day.DayOfWeek)
{
case DayOfWeek.Monday: return day.AddDays(-1);
case DayOfWeek.Tuesday: return day.AddDays(-2);
case DayOfWeek.Wednesday: return day.AddDays(-3);
case DayOfWeek.Thursday: return day.AddDays(-4);
case DayOfWeek.Friday: return day.AddDays(-5);
case DayOfWeek.Saturday: return day.AddDays(-6);
case DayOfWeek.Sunday: return day.AddDays(-7);
}
return day;
}

public static List<Appointment> SplitAppointment(Appointment appt)
{
TimeSpan oneDay = TimeSpan.FromDays(1);
TimeSpan endOfDay = oneDay; // last possible time of a day
List<Appointment> result = new List<Appointment>();
DateTime currentDay = appt.StartDate;
DateTime endOfCurrentDay = currentDay.Date + endOfDay;
while (endOfCurrentDay < appt.EndDate)
{
result.Add(new Appointment() { StartDate = currentDay, EndDate = endOfCurrentDay });
// copy other attributes of appt
currentDay = currentDay.Date + oneDay; // EDIT: changed this line
endOfCurrentDay += oneDay;
}
if (currentDay < appt.EndDate)
{
result.Add(new Appointment() { StartDate = currentDay, EndDate = appt.EndDate });
// copy other attributes of appt
}
return result;
}

/// <summary>
/// 计算某日起始日期(礼拜一的日期)
/// </summary>
/// <param name="someDate">该周中任意一天</param>
/// <returns>返回礼拜一日期,后面的具体时、分、秒和传入值相等</returns>
public static DateTime GetMondayDate(this DateTime someDate)
{
int i = someDate.DayOfWeek - DayOfWeek.Monday;
if (i == -1) i = 6;// i值 > = 0 ,因为枚举原因,Sunday排在最前,此时Sunday-Monday=-1,必须+7=6。
TimeSpan ts = new TimeSpan(i, 0, 0, 0);
return someDate.Subtract(ts);
}

/// <summary>
/// UTC时间戳起点
/// </summary>
public static readonly DateTime UTCZero = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

/// <summary>
/// 时间转换为时间戳,秒
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static long ToTimestamp(this DateTime time)
{
return (long)(time.ToUniversalTime() - UTCZero).TotalSeconds;
}
/// <summary>
/// 时间转换为时间戳,毫秒
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static long ToTimestampMilliseconds(this DateTime time)
{
return (time.ToUniversalTime() - UTCZero).Milliseconds;
}
/// <summary>
/// 时间戳转换为UTC时间
/// </summary>
/// <param name="timestamp"></param>
/// <returns></returns>
public static DateTime ToUTCTime(this long timestamp)
{
return UTCZero.AddSeconds(timestamp);
}

/// <summary>
/// 时间戳转换为本地时间
/// </summary>
/// <param name="timestamp"></param>
/// <returns></returns>
public static DateTime ToLocalTime(this long timestamp)
{
return ToUTCTime(timestamp).ToLocalTime();
}

static readonly DateTime unix_time_zero = new DateTime(1970, 1, 1);

public static TimeSpan GetUnixTimeSpan(DateTime utcTime)
{
return utcTime - unix_time_zero;
}

public static TimeSpan GetUnixTimeSpanFromNow()
{
return GetUnixTimeSpan(DateTime.UtcNow);
}

public static DateTime UnixTimeStampToDateTime(this long unixTimeStamp)
{
// Unix timestamp is seconds past epoch
var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
try
{
dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
}
catch { }
return dtDateTime;
}

public static DateTime MillisecondsToDateTime(this long milliseconds)
{
// Unix timestamp is seconds past epoch
var dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
try
{
dtDateTime = dtDateTime.AddMilliseconds(milliseconds).ToLocalTime();
}
catch { }
return dtDateTime;
}

/// <summary>
/// 距离1970/1/1的秒数,UTC时间
/// </summary>
/// <param name="utcTime"></param>
/// <returns></returns>
public static long GetUnixTimeStamp(this DateTime utcTime)
{
return (long)GetUnixTimeSpan(utcTime).TotalSeconds;
}

/// <summary>
/// 获取本地时间utc时间戳
/// </summary>
/// <param name="localTime"></param>
/// <returns></returns>
public static long GetLocalTimeUnixTimeStamp(this DateTime localTime)
{
return (long)GetUnixTimeSpan(localTime.ToUniversalTime()).TotalSeconds;
}

/// <summary>
/// 距离1970/1/1的毫秒数,UTC时间
/// </summary>
/// <param name="utcTime"></param>
/// <returns></returns>
public static long GetUnixTimeMillisecondsStamp(this DateTime utcTime)
{
return (long)GetUnixTimeSpan(utcTime).TotalMilliseconds;
}

/// <summary>
/// 当前距离1970/1/1的秒数,UTC时间
/// </summary>
public static long GetUnixTimeStampFromNow()
{
return (long)GetUnixTimeSpanFromNow().TotalSeconds;
}

static DateTime year2013 = new DateTime(2013, 1, 1);
public static long GetTicketsFrom2013(this DateTime time)
{
return (time - year2013).Ticks;
}

public static double GetTotalMinutesFrom2013(this DateTime time)
{
return Math.Floor((time - year2013).TotalMinutes);
}

public static DateTime GetDateTimeFrom2013TotalMinutes(this double totalMinutes)
{
return year2013.AddMinutes(totalMinutes);
}

/// <summary>
/// 获得该时间从2013-1-1开始算起的秒数,如果是2013前的时间,返回0
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static uint GetSecondsFrom2013(this DateTime time)
{
var span = (time - year2013).TotalSeconds;
if (span > 0)
{
return (uint)span;
}
return 0;
}

/// <summary>
/// 格式化显示时间为几个月,几天前,几小时前,几分钟前,或几秒前
/// 页面使用
/// </summary>
public static string DateStringFromNow(DateTime dt)
{
TimeSpan span = DateTime.Now - dt;
if (span.TotalDays > 365)
{
return dt.ToShortDateString();
}
else if (span.TotalDays > 30)
{
return String.Format("{0}个月前", (int)Math.Floor(span.TotalDays / 30));
}
else if (span.TotalDays > 14)
{
return "2周前";
}
else if (span.TotalDays > 7)
{
return "1周前";
}
else if (span.TotalDays > 1)
{
return String.Format("{0}天前", (int)Math.Floor(span.TotalDays));
}
else if (span.TotalHours > 1)
{
return String.Format("{0}小时前", (int)Math.Floor(span.TotalHours));
}
else if (span.TotalMinutes > 1)
{
return String.Format("{0}分钟前", (int)Math.Floor(span.TotalMinutes));
}
else if (span.TotalSeconds >= 1)
{
return String.Format("{0}秒前", (int)Math.Floor(span.TotalSeconds));
}
else
{
return "1秒前";
}
}

public static int GetIso8601WeekOfYear(this DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}
// Return the week of our adjusted day
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}

public static DateTime GetCurrentMonth(this DateTime day)
{
return new DateTime(day.Year, day.Month, 1);
}

public static bool IsMonthLastDay(this DateTime day)
{
return day.Date == new DateTime(day.Year, day.Month, 1).AddMonths(1).AddDays(-1);
}

public static DateTime StampToDateTime(string timeStamp)
{
DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000");
TimeSpan toNow = new TimeSpan(lTime);
return dateTimeStart.Add(toNow);
}
public static string RsetDateTimeStr(string dateTime)
{
const string defalut1 = "1901/1/1 0:00:00";
const string defalut2 = "0001/1/1 0:00:00";
if (dateTime == defalut1 || dateTime == defalut2)
{
return string.Empty;
}
else
{
return dateTime;
}

}

// <summary>
/// 计算本周起始日期(礼拜一的日期)
/// </summary>
/// <param name="someDate">该周中任意一天</param>
/// <returns>返回礼拜一日期,后面的具体时、分、秒和传入值相等</returns>
public static DateTime CalculateFirstDateOfWeek(DateTime someDate)
{
int i = someDate.DayOfWeek - DayOfWeek.Monday;
if (i == -1) i = 6;// i值 > = 0 ,因为枚举原因,Sunday排在最前,此时Sunday-Monday=-1,必须+7=6。
TimeSpan ts = new TimeSpan(i, 0, 0, 0);
return someDate.Subtract(ts);
}

/// <summary>
/// 计算本周结束日期(礼拜日的日期)
/// </summary>
/// <param name="someDate">该周中任意一天</param>
/// <returns>返回礼拜日日期,后面的具体时、分、秒和传入值相等</returns>
public static DateTime CalculateLastDateOfWeek(DateTime someDate)
{
int i = someDate.DayOfWeek - DayOfWeek.Sunday;
if (i != 0) i = 7 - i;// 因为枚举原因,Sunday排在最前,相减间隔要被7减。
TimeSpan ts = new TimeSpan(i, 0, 0, 0);
return someDate.Add(ts);
}

/// <summary>
/// 判断选择的日期是否是本周(根据系统当前时间决定的‘本周'比较而言)
/// </summary>
/// <param name="someDate"></param>
/// <returns></returns>
public static bool IsThisWeek(DateTime someDate)
{
//得到someDate对应的周一
DateTime someMon = CalculateFirstDateOfWeek(someDate);
//得到本周一
DateTime nowMon = CalculateFirstDateOfWeek(DateTime.Now);
TimeSpan ts = someMon - nowMon;
if (ts.Days < 0)
ts = -ts;//取正
if (ts.Days >= 7)
{
return false;
}
else
{
return true;
}
}

/// <summary>
///获取当前日期在一周里的第几天,sunday默认为0,转换为7
/// </summary>
/// <param name="now"></param>
/// <returns></returns>
public static string GetDayOfWeek(this DateTime now)
{
return now.DayOfWeek == DayOfWeek.Sunday ? "7" : now.DayOfWeek.ToString("D");
}

/// <summary>
/// 时间拼接时分秒 时间2017-06-27 00:00:00 转换后变成2017-06-27 23:59:59
/// </summary>
/// <param name="now"></param>
/// <returns></returns>
public static DateTime AppendDateHMS(this DateTime now)
{
return now.AddHours(23).AddMinutes(59).AddSeconds(59);
}

/// <summary>
/// 获取当前时间,精确到小时
/// </summary>
/// <returns></returns>
public static DateTime GetCurrentHourTime()
{
var now = DateTime.Now;
var time = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0);
return time;
}

public static string GetTimeStamp(this DateTime dateTime)
{
return ((Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString();
}

private static DateTime MySqlNullDatetime = new DateTime(1, 1, 1, 0, 0, 0);
public static bool IsMySqlDateTimeNull(this DateTime @this)
{
return MySqlNullDatetime == @this;
}

DatetimeHelper类的编写的更多相关文章

  1. ReflectUitls类的编写和对反射机制的解析

    ReflectUitls类的编写和对反射机制的解析 反射相关的类 反射相关的类,最基本的当然是Class类. 获取了Class对象之后,就可以接着生成对象实例.调用方法.查看字段等等. 字段(Fiel ...

  2. c#中sqlhelper类的编写(二)

    上一篇文章讲了简易版的SqlHelper类的编写,我们在这里就上一篇文章末尾提出的问题写出解决方案. sql语句注入攻击已经是众所周知的了.我们如何在C#中保护自己的数据库不被这样的方式攻击呢? 不用 ...

  3. 20140902 字符串拷贝函数 右旋转字符串 string类的编写

    1.strncpy字符串拷贝函数 //strncpy的程序 #include<stdio.h> #include<assert.h> char *strncpy1(char * ...

  4. P145MathTool测试类的编写

    如果我们在方法的自变量个数事先无法决定如何处理,比如: System.out.printf("%d",10); System.out.printf("%d %d" ...

  5. C++Array类模板编写笔记

    C++Array类模板 函数模板和类模板都属于泛型技术,利用函数模板和类模板来创建一个具有通用功能的函数和类,以支持多种不同的形参,从而进一步简化重载函数的函数体设计. 声明方法:template&l ...

  6. java类及编写public类的基础点

    1.一个java文件中只能有一个public类.且公共类名称必须与java文件名一致,否则会出现错误提示.与其他面向对象编程语言的一样,在利用java分析问题时,基本思路即为将问题的属性(静)与行为( ...

  7. Struts2 | struts.xml文件中使用method属性和通配符简化action标签和Action处理类的编写

    转自:https://www.jianshu.com/p/310e89ee762d 在Struts2框架中,我们知道基本的Action标签只能实现一个url请求对应一个Action处理类.那么我们如果 ...

  8. 类的编写模板之简单Java类

    简单Java类是初学java时的一个重要的类模型,一般由属性和getter.setter方法组成,该类不涉及复杂的逻辑运算,仅仅是作为数据的储存,同时该类一般都有明确的实物类型.如:定义一个雇员的类, ...

  9. c#中sqlhelper类的编写(一)

    在.net平台的项目开发中,凡是用到数据库交互的,都有必要了解SqlHelper类的原理. 步骤一: 我就拿WPF项目开发作为例子.首先要新建一个App.config(应用程序配置文件).注意,在VS ...

随机推荐

  1. Redis缓存和MySQL数据一致性方案(转)

    需求起因 在高并发的业务场景下,数据库大多数情况都是用户并发访问最薄弱的环节.所以,就需要使用redis做一个缓冲操作,让请求先访问到redis,而不是直接访问MySQL等数据库. 这个业务场景,主要 ...

  2. pytest文档29-allure-pytest(最新最全,保证能搞成功!)

    前言 之前写了个pytest的allure相关的教程,只是停留在环境搭建完成,后续一直没用,小编一直不喜欢这种花里胡哨的报告. 没办法,领导就喜欢这种,小伙伴们也喜欢,所以还是得把allure用起来, ...

  3. pdfium 之二

    https://www.foxitsoftware.cn/products/premium-pdfium/feature.php 基于谷歌PDFium开源代码 谷歌采用福昕的PDF技术为其PDF开源项 ...

  4. V4l2初识(七)-----------浅析app获取虚拟摄像头数据的过程

    继续分析数据的获取过程: 1.请求分配的缓冲区: ioctl(4,VIDIOC_REQBUFS) vidioc_reqbufs 2.查询和映射缓冲区   ioctl(4,VIDIOC_QUERYBUF ...

  5. 201871010110-李华《面向对象程序设计(java)》第十六周学习总结

    博文正文开头格式:(2分) 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.co ...

  6. echo和printf打印输出

    [root@node2 scprits]# echo Hello World! Hello World! [root@node2 scprits]# echo 'Hello World!' Hello ...

  7. Git 创建点开头的文件和目录

    Git 创建点开头的文件和目录 # 创建 .gitignore 文件 1@DESKTOP-3H9092J MINGW64 /e/x1/x1/demo1 (master) $ echo .idea &g ...

  8. 0629 Flink Meetup 北京站 PPT下载

    工程实用问题解决方案介绍,实用

  9. JDOJ 2254 Who am I?

    JDOJ 2254: Who am I? Description 输出程序自己本身的源代码. Input 无 Output 输出程序自己本身的源代码. 我真是搞不懂了出这道题还把它归到程序语法基础题里 ...

  10. 基于OpenVINO的多输入model optimizer(Tensorflow)

    Step I:下载预训练模型 wget -O - https://github.com/mozilla/DeepSpeech/releases/download/v0.3.0/deepspeech-0 ...