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 ...
随机推荐
- 团队作业第3周——需求改进&系统设计(crtl冲锋队)
2.需求&原型改进: 1.问题:游戏中我方飞机和敌方飞机是怎么控制的? 改进: 在游戏中,我控制我方飞机,按下方向键飞机便向按下的方向移动,按下Z键,我方飞机发射子弹. 敌方飞机面向随机的方向 ...
- Linux环境oracle导库步骤
1.xshell登录linux 2.切换oracle用户 su - oracle 3.创建directory仓库目录,存放数据库dmp文件 //DIRFILE_zy 表示目录名称 后面的是实际地址 c ...
- 白话SCRUM 之四:燃尽图
Burn down chart翻译为燃尽图或燃烧图,很形象,是Scrum中展示项目进展的一个指示器.我一直认为用户故事.每日站立会议.燃尽图.sprint review.sprint retrospe ...
- Linux7/Centos7用户密码安全
当Linux7/Centos7的用户root密码常用如下方式找回密码: 第一步:按e键进入内核启动页面如下: 第二步:在linux16一行LANG=zh_CN.UTF-8后面加rd.break con ...
- 其他综合-CentOS 7 命令行显示优化
CentOS 7 命令行显示优化 1.实验描述 通过 CentOS 7.6 的显示优化,为实现命令行显示提供良好视觉体验. [基于此文章的环境]点我快速打开文章 2.实验环境 使用软件的版本:VMwa ...
- 进化后的const分析
C语言中的const const修饰的变量是只读的,本质还是变量 const修饰的局部变量在栈上分配空间 const修饰的全局变量在只读存储区分配空间 const只在编译期有用,在运行期无用 注意:c ...
- java+selenium3学习
http://blog.csdn.net/u011541946/article/details/72898514 http://git.oschina.net/zhengshuheng https:/ ...
- python GIL全局解释器锁,多线程多进程效率比较,进程池,协程,TCP服务端实现协程
GIL全局解释器锁 ''' python解释器: - Cpython C语言 - Jpython java ... 1.GIL: 全局解释器锁 - 翻译: 在同一个进程下开启的多线程,同一时刻只能有一 ...
- MyBatis 插入记录同时获取主键
MyBatis 插入记录同时获取主键 MyBatis 插入记录同时获取主键的系统界面 useGeneratedKeys 属性 keyProperty 属性 keyColumn 属性 selectKey ...
- NOIP 2002 产生数
洛谷 P1037 产生数 https://www.luogu.org/problemnew/show/P1037 JDOJ 1298: [NOIP2002]产生数 T3 https://neooj.c ...