C# 日期帮助类
using System;
using System.Data; namespace Erp.Ship.Tool
{
[Serializable]
public enum DateInterval
{
Second, Minute, Hour, Day, Week, Month, Quarter, Year
}
/// <summary>
/// 日期处理工具类
/// </summary>
[Serializable]
public class DateUtil
{
private DateUtil(){ }
private static readonly string ISO8601Short = "yyyy-MM-dd";
private static readonly string ISO8601Long = "yyyy-MM-dd HH:mm:ss";
/// <summary>
/// 从计划配置取得本周从星期几开始
/// </summary>
/// <returns></returns>
public static DayOfWeek GetFirstDayOfWeek()
{
DayOfWeek firstDayOfWeek = DayOfWeek.Monday; DataRow[] drs = PlanUtil.SYS_DT.Select("attribute_name = 'Week_Start_Day'");
if (drs != null && drs.Length > 0)
{
string ATTRIBUTE_VALUE = drs[0]["ATTRIBUTE_VALUE"].ToString();
switch (ATTRIBUTE_VALUE)
{
case "0":
firstDayOfWeek = DayOfWeek.Sunday;
break;
case "1":
firstDayOfWeek = DayOfWeek.Monday;
break;
case "2":
firstDayOfWeek = DayOfWeek.Tuesday;
break;
case "3":
firstDayOfWeek = DayOfWeek.Wednesday;
break;
case "4":
firstDayOfWeek = DayOfWeek.Thursday;
break;
case "5":
firstDayOfWeek = DayOfWeek.Friday;
break;
case "6":
firstDayOfWeek = DayOfWeek.Saturday;
break;
default:
break;
}
} return firstDayOfWeek;
}
/// <summary>
/// 根据日期取得当前周次
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static int GetWeekOfYear(DateTime dt)
{
System.Globalization.GregorianCalendar gc = new System.Globalization.GregorianCalendar();
DayOfWeek firstDayOfWeek = GetFirstDayOfWeek(); int weekOfYear = gc.GetWeekOfYear(dt, System.Globalization.CalendarWeekRule.FirstDay, firstDayOfWeek); return weekOfYear;
}
/// <summary>
/// 根据日期获取一个周期(7天)的开始日期
/// </summary>
/// <param name="cd"></param>
/// <returns></returns>
public static DateTime getStartDate(DateTime cd)
{ string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
switch (Day[Convert.ToInt16(DateTime.Now.DayOfWeek)])
{
case "星期日": return cd.AddDays(-9);
case "星期一": return cd.AddDays(-10);
case "星期二": return cd.AddDays(-11);
case "星期三": return cd.AddDays(-12);
case "星期四": return cd.AddDays(-13);
case "星期五": return cd.AddDays(-7);
case "星期六": return cd.AddDays(-8);
}
return cd;
}
/// <summary>
/// 根据日期获取一个周期(7天)的结束日期
/// </summary>
/// <param name="cd"></param>
/// <returns></returns>
public static DateTime getEndDate(DateTime cd)
{
int t = Convert.ToInt16(cd.DayOfWeek);
switch (t)
{
case 0: return cd.AddDays(-3);
case 1: return cd.AddDays(-4);
case 2: return cd.AddDays(-5);
case 3: return cd.AddDays(-6);
case 4: return cd.AddDays(-7);
case 5: return cd.AddDays(-1);
case 6: return cd.AddDays(-2); }
return cd;
}
/// <summary>
/// 判断 字符对象 是否是日期字符
/// </summary>
/// <param name="obj">字符对象</param>
/// <returns></returns>
public static bool isDate(object obj)
{
bool tag = false;
try
{
if (obj != null)
{
Convert.ToDateTime(obj.ToString());
tag = true;
}
}
catch (Exception)
{
}
return tag;
}
public static string toStr(object obj)
{
try
{
if (obj == null || obj == DBNull.Value)
{
return string.Empty;
}
else
{
return Convert.ToDateTime(obj.ToString()).ToString(DateUtil.ISO8601Short);
}
}
catch (Exception)
{
return string.Empty;
}
}
public static string toLongStr(object obj)
{
try
{
if (obj == null || obj == DBNull.Value)
{
return string.Empty;
}
else
{
return Convert.ToDateTime(obj.ToString()).ToString(DateUtil.ISO8601Long);
}
}
catch (Exception)
{
return string.Empty;
}
}
/// <summary>
/// 将日期对象转换成日期
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static DateTime toDate(object obj)
{
try
{
if (obj != null)
{
return Convert.ToDateTime(obj.ToString().Trim());
}
else
{
return DateTime.MinValue;
}
}
catch (Exception)
{
return DateTime.MinValue;
} }
/// <summary>
/// 实现类似数据库 DateDiff 功能
/// </summary>
/// <param name="Interval">间隔类型</param>
/// <param name="StartDate">开始日期</param>
/// <param name="EndDate">结束日期</param>
/// <returns></returns>
public static long DateDiff(DateInterval Interval, System.DateTime StartDate, System.DateTime EndDate)
{
long lngDateDiffValue = 0;
System.TimeSpan TS = new System.TimeSpan(EndDate.Ticks - StartDate.Ticks);
switch (Interval)
{
case DateInterval.Second:
lngDateDiffValue = (long)TS.TotalSeconds;
break;
case DateInterval.Minute:
lngDateDiffValue = (long)TS.TotalMinutes;
break;
case DateInterval.Hour:
lngDateDiffValue = (long)TS.TotalHours;
break;
case DateInterval.Day:
lngDateDiffValue = (long)TS.Days;
break;
case DateInterval.Week:
lngDateDiffValue = (long)(TS.Days / 7);
break;
case DateInterval.Month:
lngDateDiffValue = (long)(TS.Days / 30);
break;
case DateInterval.Quarter:
lngDateDiffValue = (long)((TS.Days / 30) / 3);
break;
case DateInterval.Year:
lngDateDiffValue = (long)(TS.Days / 365);
break;
}
return (lngDateDiffValue);
}
public static string toColorStr(object obj)
{
string temp = "";
try
{
if (obj != null)
{
DateTime dt = Convert.ToDateTime(obj.ToString());
if (dt.Year == 2011)
{
temp = "<span class='x-grid-back-red1'>" + dt.ToString(DateUtil.ISO8601Short) + "</span>";
}
if (dt.Year == 2012)
{
temp = "<span class='x-grid-back-red2'>" + dt.ToString(DateUtil.ISO8601Short) + "</span>";
}
if (dt.Year == 2013)
{
temp = "<span class='x-grid-back-red3'>" + dt.ToString(DateUtil.ISO8601Short) + "</span>";
}
if (dt.Year == 2014)
{
temp = "<span class='x-grid-back-red4'>" + dt.ToString(DateUtil.ISO8601Short) + "</span>";
} }
}
catch (Exception)
{
}
return temp;
}
/// <summary>
/// 获取该年中是第几周
/// </summary>
/// <param name="day">日期</param>
/// <returns></returns>
public static int WeekOfYear(System.DateTime day)
{
int weeknum;
System.DateTime fDt = DateTime.Parse(day.Year.ToString() + "-01-01");
int k = Convert.ToInt32(fDt.DayOfWeek);//得到该年的第一天是周几
if (k == 0)
{
k = 7;
}
int l = Convert.ToInt32(day.DayOfYear);//得到当天是该年的第几天
l = l - (7 - k + 1);
if (l <= 0)
{
weeknum = 1;
}
else
{
if (l % 7 == 0)
{
weeknum = l / 7 + 1;
}
else
{
weeknum = l / 7 + 2;//不能整除的时候要加上前面的一周和后面的一周
}
}
return weeknum;
} public static string GetFirstDayOfWeekVal()
{
string ATTRIBUTE_VALUE = "1"; DataRow[] drs = PlanUtil.SYS_DT.Select("attribute_name = 'Week_Start_Day'");
if (drs != null && drs.Length > 0)
{
ATTRIBUTE_VALUE = drs[0]["ATTRIBUTE_VALUE"].ToString();
} return ATTRIBUTE_VALUE;
} /// <summary>
/// 获取该年中是第几季度
/// </summary>
/// <param name="day">日期</param>
/// <returns></returns>
public static int QuarterOfYear(System.DateTime day)
{
if (day.Month < 4)
{
return 1;
}
else if (day.Month > 9)
{
return 4;
}
else if (day.Month > 3 && day.Month < 7)
{
return 2;
}
else
{
return 3;
}
}
/// <summary>
/// 计算日期间隔
/// </summary>
/// <param name="d1">要参与计算的其中一个日期字符串</param>
/// <param name="d2">要参与计算的另一个日期字符串</param>
/// <returns>一个表示日期间隔的TimeSpan类型</returns>
public static TimeSpan toResult(string d1, string d2)
{
try
{
DateTime date1 = DateTime.Parse(d1);
DateTime date2 = DateTime.Parse(d2);
return toResult(date1, date2);
}
catch
{
throw new Exception("字符串参数不正确!");
}
}
/// <summary>
/// 计算日期间隔
/// </summary>
/// <param name="d1">要参与计算的其中一个日期</param>
/// <param name="d2">要参与计算的另一个日期</param>
/// <returns>一个表示日期间隔的TimeSpan类型</returns>
public static TimeSpan toResult(DateTime d1, DateTime d2)
{
TimeSpan ts;
if (d1 > d2)
{
ts = d1 - d2;
}
else
{
ts = d2 - d1;
}
return ts;
} /// <summary>
/// 计算日期间隔
/// </summary>
/// <param name="d1">要参与计算的其中一个日期字符串</param>
/// <param name="d2">要参与计算的另一个日期字符串</param>
/// <param name="drf">决定返回值形式的枚举</param>
/// <returns>一个代表年月日的int数组,具体数组长度与枚举参数drf有关</returns>
public static int[] toResult(string d1, string d2, diffResultFormat drf)
{
try
{
DateTime date1 = DateTime.Parse(d1);
DateTime date2 = DateTime.Parse(d2);
return toResult(date1, date2, drf);
}
catch
{
throw new Exception("字符串参数不正确!");
}
}
/// <summary>
/// 计算日期间隔
/// </summary>
/// <param name="d1">要参与计算的其中一个日期</param>
/// <param name="d2">要参与计算的另一个日期</param>
/// <param name="drf">决定返回值形式的枚举</param>
/// <returns>一个代表年月日的int数组,具体数组长度与枚举参数drf有关</returns>
public static int[] toResult(DateTime d1, DateTime d2, diffResultFormat drf)
{
#region 数据初始化
DateTime max;
DateTime min;
int year;
int month;
int tempYear, tempMonth;
if (d1 > d2)
{
max = d1;
min = d2;
}
else
{
max = d2;
min = d1;
}
tempYear = max.Year;
tempMonth = max.Month;
if (max.Month < min.Month)
{
tempYear--;
tempMonth = tempMonth + 12;
}
year = tempYear - min.Year;
month = tempMonth - min.Month;
#endregion
#region 按条件计算
if (drf == diffResultFormat.dd)
{
TimeSpan ts = max - min;
return new int[] { ts.Days };
}
if (drf == diffResultFormat.mm)
{
return new int[] { month + year * 12 };
}
if (drf == diffResultFormat.yy)
{
return new int[] { year };
}
return new int[] { year, month };
#endregion
} /// <summary>
/// 获取指定年月的最后一天
/// </summary>
/// <param name="year">年份</param>
/// <param name="month">月份</param>
/// <returns></returns>
public static int GetLastDayofMonth(int year, int month)
{
int days = DateTime.DaysInMonth(year, month);
DateTime datetime = new DateTime(year, month, 1);
return datetime.AddDays(days - 1).Day;
} /// <summary>
/// 获取指定日期所在周的第一天,星期天为第一天
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime GetDateTimeWeekFirstDaySun(DateTime dateTime)
{
DateTime firstWeekDay = DateTime.Now; try
{
//得到是星期几,然后从当前日期减去相应天数
int weeknow = Convert.ToInt32(dateTime.DayOfWeek); int daydiff = (-1) * weeknow; firstWeekDay = dateTime.AddDays(daydiff);
}
catch { } return firstWeekDay;
} /// <summary>
/// 获取指定日期所在周的第一天,星期一为第一天
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime GetDateTimeWeekFirstDayMon(DateTime dateTime)
{
DateTime firstWeekDay = DateTime.Now; try
{
int weeknow = Convert.ToInt32(dateTime.DayOfWeek); //星期一为第一天,weeknow等于0时,要向前推6天。
weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1)); int daydiff = (-1) * weeknow; firstWeekDay = dateTime.AddDays(daydiff);
}
catch { } return firstWeekDay;
} /// <summary>
/// 获取指定日期所在周的最后一天,星期六为最后一天
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime GetDateTimeWeekLastDaySat(DateTime dateTime)
{
DateTime lastWeekDay = DateTime.Now; try
{
int weeknow = Convert.ToInt32(dateTime.DayOfWeek); int daydiff = (7 - weeknow) - 1; lastWeekDay = dateTime.AddDays(daydiff); }
catch { } return lastWeekDay;
} /// <summary>
/// 获取指定日期所在周的最后一天,星期天为最后一天
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns> public static DateTime GetDateTimeWeekLastDaySun(DateTime dateTime)
{
DateTime lastWeekDay = DateTime.Now; try
{
int weeknow = Convert.ToInt32(dateTime.DayOfWeek); weeknow = (weeknow == 0 ? 7 : weeknow); int daydiff = (7 - weeknow); lastWeekDay = dateTime.AddDays(daydiff);
}
catch { } return lastWeekDay;
} /// <summary>
/// 获取指定日期的月份第一天
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime GetDateTimeMonthFirstDay(DateTime dateTime)
{
if (dateTime == null)
{
dateTime = DateTime.Now;
} return new DateTime(dateTime.Year, dateTime.Month, 1);
} /// <summary>
/// 获取指定月份最后一天
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public static DateTime GetDateTimeMonthLastDay(DateTime dateTime)
{
int day = DateTime.DaysInMonth(dateTime.Year, dateTime.Month); return new DateTime(dateTime.Year, dateTime.Month, day);
}
}
} /// <summary>
/// 关于返回值形式的枚举
/// </summary>
public enum diffResultFormat
{
/// <summary>
/// 年数和月数
/// </summary>
yymm,
/// <summary>
/// 年数
/// </summary>
yy,
/// <summary>
/// 月数
/// </summary>
mm,
/// <summary>
/// 天数
/// </summary>
dd,
}
C# 日期帮助类的更多相关文章
- Android随笔之——Android时间、日期相关类和方法
今天要讲的是Android里关于时间.日期相关类和方法.在Android中,跟时间.日期有关的类主要有Time.Calendar.Date三个类.而与日期格式化输出有关的DateFormat和Simp ...
- Java 日期格式化工具类
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; impor ...
- 日期操作类--SimpleDateFormat类
使用SimpleDateFormat格式化日期 SimpleDateFormat是一个以语言环境敏感的方式来格式化和分析日期的类.SimpleDateFormat允许你选择任何用户自定义日期时间格式来 ...
- 日期操作类--Date类
Date-API ava.util包提供了Date类来封装当前的日期和时间.Date类提供两个构造函数来实例化Date对象.第一个构造函数使用当前日期和时间来初始化对象. Date( ) 第二个构造函 ...
- 日期转换类 DateConverter.java
package com.util; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.D ...
- 日期工具类 - DateUtil.java
日期工具类,提供对日期的格式化和转换方法.获取区间日期.指定日期.每月最后一天等. 源码如下:(点击下载 -DateUtil.java.commons-lang-2.6.jar ) import ja ...
- C++实现日期转换类DateTime
概述 工作中我们在网络传输时使用time_t来传输时间,在显示时使用字符串来显示,下面是一个日期转换类的实现,方便以后使用: // DateTime.hpp #ifndef _DATETIME_H # ...
- JS 日期工具类-基于yDate
源码下载 前言:最近在用到JS日期操作时,发现有一些不方便,于是搜素了一些网上的资料,基于一个开源工具类-yDate 进行了个性化定制,封装成了一个日期工具类工具函数大概介绍:1.普通的日期操作2. ...
- C#日期转换类
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Te ...
- Java日期工具类,Java时间工具类,Java时间格式化
Java日期工具类,Java时间工具类,Java时间格式化 >>>>>>>>>>>>>>>>>&g ...
随机推荐
- leaflet利用hotline实现河流差值渲染热力图
实现效果(这里做了1条主河道和5个支流): 核心代码使用了Leaflet.hotline插件,github下载地址链接 详情见我之前整理的一篇文章介绍河流热力图 核心代码逻辑: // 处理河流数据以及 ...
- 关于小说阅读前端翻页插件推荐turn.js
http://www.turnjs.com
- Chrome 浏览器插件 Manifest.json V3 中权限(Permissions)字段解析
一.权限(Permissions) 再使用拓展程序的 API 时,大多数的时候,需要在 manifest.json 文件中声明 permissions 字段. 一.权限类型 在 V3 版本中可以声明以 ...
- NODEJS通过发送json数据查询目标服务,实现服务器状态监控,发现异常发送到微信群提醒
root@aea87fa6e6a2:/home/node# cat login2.js const request = require('request-promise'); const moment ...
- Doug Lea大师的佳作CopyOnWriteArrayList,用不好能坑死你!
一.写在开头 我们在学习集合或者说容器的时候了解到,很多集合并非线程安全的,在并发场景下,为了保障数据的安全性,诞生了并发容器,广为人知的有ConcurrentHashMap.ConcurrentLi ...
- GROK 表达式
GROK 表达式 常用表达式 标识:USERNAME 或 USER 正则:[a-zA-Z0-9._-]+ 名称:用户名 描述:由数字.大小写及特殊字符(._-)组成的字符串 例子:1234.Bob.A ...
- 分享一个Objectarx 的凸包算法
#include "stdafx.h" #include "MyTuBao.h" #include"MathUtil.h" MyTuBao: ...
- [N1盒子] Armbian安装Docker+Portainer汉化面板支持小钢炮汉化+中英文切换方法
1.下载汉化包,解压后备用链接:https://pan.baidu.com/s/1BLXMSmJFcgESeNMhQL26Mg&shfl=sharepset提取码:6vjr 以下安装,国内建议 ...
- 【阿里天池云-龙珠计划】薄书的机器学习笔记——快来一起挖掘幸福感!Task04
[给各位看官请安] 大家一起来集齐七龙珠召唤神龙吧!!! 学习地址:AI训练营机器学习-阿里云天池 推荐一下我由此上车的公众号:AI蜗牛车,时空序列相关文章挺多的. Task01:基于逻辑回归模型的多 ...
- itest(爱测试)开源接口测试&敏捷测试管理平台8.1.0发布
(一)itest 简介 itest 开源敏捷测试管理,testOps 践行者,极简的任务管理,测试管理,缺陷管理,测试环境管理,接口测试,接口Mock 6合1,又有丰富的统计分析.可按测试包分配测试用 ...