DatetimeHelper类的编写
公共类 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类的编写的更多相关文章
- ReflectUitls类的编写和对反射机制的解析
ReflectUitls类的编写和对反射机制的解析 反射相关的类 反射相关的类,最基本的当然是Class类. 获取了Class对象之后,就可以接着生成对象实例.调用方法.查看字段等等. 字段(Fiel ...
- c#中sqlhelper类的编写(二)
上一篇文章讲了简易版的SqlHelper类的编写,我们在这里就上一篇文章末尾提出的问题写出解决方案. sql语句注入攻击已经是众所周知的了.我们如何在C#中保护自己的数据库不被这样的方式攻击呢? 不用 ...
- 20140902 字符串拷贝函数 右旋转字符串 string类的编写
1.strncpy字符串拷贝函数 //strncpy的程序 #include<stdio.h> #include<assert.h> char *strncpy1(char * ...
- P145MathTool测试类的编写
如果我们在方法的自变量个数事先无法决定如何处理,比如: System.out.printf("%d",10); System.out.printf("%d %d" ...
- C++Array类模板编写笔记
C++Array类模板 函数模板和类模板都属于泛型技术,利用函数模板和类模板来创建一个具有通用功能的函数和类,以支持多种不同的形参,从而进一步简化重载函数的函数体设计. 声明方法:template&l ...
- java类及编写public类的基础点
1.一个java文件中只能有一个public类.且公共类名称必须与java文件名一致,否则会出现错误提示.与其他面向对象编程语言的一样,在利用java分析问题时,基本思路即为将问题的属性(静)与行为( ...
- Struts2 | struts.xml文件中使用method属性和通配符简化action标签和Action处理类的编写
转自:https://www.jianshu.com/p/310e89ee762d 在Struts2框架中,我们知道基本的Action标签只能实现一个url请求对应一个Action处理类.那么我们如果 ...
- 类的编写模板之简单Java类
简单Java类是初学java时的一个重要的类模型,一般由属性和getter.setter方法组成,该类不涉及复杂的逻辑运算,仅仅是作为数据的储存,同时该类一般都有明确的实物类型.如:定义一个雇员的类, ...
- c#中sqlhelper类的编写(一)
在.net平台的项目开发中,凡是用到数据库交互的,都有必要了解SqlHelper类的原理. 步骤一: 我就拿WPF项目开发作为例子.首先要新建一个App.config(应用程序配置文件).注意,在VS ...
随机推荐
- 4.dubbo 的 spi 思想是什么?
作者:中华石杉 面试题 dubbo 的 spi 思想是什么? 面试官心理分析 继续深入问呗,前面一些基础性的东西问完了,确定你应该都 ok,了解 dubbo 的一些基本东西,那么问个稍微难一点点的问题 ...
- 查看 JVM 默认参数
-XX:+PrintFlagsFinal 可以获取所有可设置参数及值 获取 JVM 默认 Xss 大小 java -XX:+PrintFlagsFinal -version | grep Thread ...
- [TCP/IP] TCP在listen时的参数backlog的意义
linux内核中会维护两个队列: 1)未完成队列:接收到一个SYN建立连接请求,处于SYN_RCVD状态 2)已完成队列:已完成TCP三次握手过程,处于ESTABLISHED状态 3)当有一个S ...
- linux(10)uwsgi???
[uwsgi] Django-related settings the base directory (full path) #指定项目的绝对路径的第一层路径!!!!!!!!!!!!!!!!!!!!! ...
- pdfium
https://github.com/SubtleCow/AccessControlListsintheDOM/tree/4673d995e5614bc682cecd22f9b2919b2360273 ...
- 0629 Flink Meetup 北京站 PPT下载
工程实用问题解决方案介绍,实用
- nexus php composer 私服搭建
nexus 社区也提供了php composer 私服(当前还在开发中,还没有ga),测试使用构建好的docker 镜像 环境准备 docker-compose 文件 version: "3 ...
- B1047 编程团体赛 (20 分)
一.参考代码 #include<iostream> #include<cstring> using namespace std; int hashTable[1010]; in ...
- 解决PEnetwork启动的时候提示"An error occured while starting the "TCP/IP Registry Compatibility" Service (2)!"程序将立即退出的问题
解决PEnetwork启动的时候提示"An error occured while starting the "TCP/IP Registry Compatibility" ...
- Linux性能优化实战学习笔记:第三十一讲
一.上节回顾 上一节,我们一起回顾了常见的文件系统和磁盘 I/O 性能指标,梳理了核心的 I/O 性能观测工具,最后还总结了快速分析 I/O 性能问题的思路. 虽然 I/O 的性能指标很多,相应的性能 ...