如何获取本周,本月,本日的开始时间和结束时间的时间戳

合集下载

计算机系统时间提取的正确方法

计算机系统时间提取的正确方法

计算机系统时间提取的正确方法
正确提取计算机系统时间的方法取决于应用场景和需求。

以下是几种常见的方法:
1. 使用系统调用函数:在 C 语言中,可以使用系统调用函数gettimeofday() 来获取当前系统时间。

该函数会返回两个值,分别是秒和毫秒,它们可以用于计算时间差。

2. 使用计时器:可以使用计时器来定期获取当前时间,并将其记录下来。

这种方法适用于需要频繁获取时间的场景,例如实时监控和统计。

3. 使用日志文件:操作系统通常会生成日志文件,记录各种事件和时间戳。

可以使用日志分析工具来提取时间信息,以帮助确定时间差和时间戳。

4. 使用第三方时间库:对于一些需要高精度和时间稳定性的应用,可以使用第三方时间库,例如 time.h 库或 libtime 库。

这些库提供了各种时间测量和计算函数,可以方便地获取当前时间。

需要根据具体应用场景选择正确的方法来提取计算机系统时间。

在实际应用中,还需要注意时间的准确性和稳定性,以确保计算结果
的正确性和可靠性。

js获取本周、上周、本月、上月、本季度、上季度的开始结束日期

js获取本周、上周、本月、上月、本季度、上季度的开始结束日期

js获取本周、上周、本⽉、上⽉、本季度、上季度的开始结束⽇期js 获取本周、上周、本⽉、上⽉、本季度、上季度的开始结束⽇期/*** 获取本周、本季度、本⽉、上⽉的开始⽇期、结束⽇期*/var now = new Date(); //当前⽇期var nowDayOfWeek = now.getDay(); //今天本周的第⼏天var nowDay = now.getDate(); //当前⽇var nowMonth = now.getMonth(); //当前⽉var nowYear = now.getYear(); //当前年nowYear += (nowYear < 2000) ? 1900 : 0; //var lastMonthDate = new Date(); //上⽉⽇期lastMonthDate.setDate(1);lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);var lastYear = lastMonthDate.getYear();var lastMonth = lastMonthDate.getMonth();//格式化⽇期:yyyy-MM-ddfunction formatDate(date) {var myyear = date.getFullYear();var mymonth = date.getMonth() + 1;var myweekday = date.getDate();if (mymonth < 10) {mymonth = "0" + mymonth;}if (myweekday < 10) {myweekday = "0" + myweekday;}return (myyear + "-" + mymonth + "-" + myweekday);}//获得某⽉的天数function getMonthDays(myMonth) {var monthStartDate = new Date(nowYear, myMonth, 1);var monthEndDate = new Date(nowYear, myMonth + 1, 1);var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);return days;}//获得本季度的开始⽉份function getQuarterStartMonth() {var quarterStartMonth = 0;if (nowMonth < 3) {quarterStartMonth = 0;}if (2 < nowMonth && nowMonth < 6) {quarterStartMonth = 3;}if (5 < nowMonth && nowMonth < 9) {quarterStartMonth = 6;}if (nowMonth > 8) {quarterStartMonth = 9;}return quarterStartMonth;}//获得本周的开始⽇期function getWeekStartDate() {var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);return formatDate(weekStartDate);}//获得本周的结束⽇期function getWeekEndDate() {var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek));return formatDate(weekEndDate);}//获得上周的开始⽇期function getLastWeekStartDate() {var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7);return formatDate(weekStartDate);}//获得上周的结束⽇期function getLastWeekEndDate() {var weekEndDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 1);return formatDate(weekEndDate);}//获得本⽉的开始⽇期function getMonthStartDate() {var monthStartDate = new Date(nowYear, nowMonth, 1);return formatDate(monthStartDate);}//获得本⽉的结束⽇期function getMonthEndDate() {var monthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowMonth));return formatDate(monthEndDate);}//获得上⽉开始时间function getLastMonthStartDate() {var lastMonthStartDate = new Date(nowYear, lastMonth, 1);return formatDate(lastMonthStartDate);}//获得上⽉结束时间function getLastMonthEndDate() {var lastMonthEndDate = new Date(nowYear, lastMonth, getMonthDays(lastMonth));return formatDate(lastMonthEndDate);}//获得本季度的开始⽇期function getQuarterStartDate() {var quarterStartDate = new Date(nowYear, getQuarterStartMonth(), 1);return formatDate(quarterStartDate);}//或的本季度的结束⽇期function getQuarterEndDate() {var quarterEndMonth = getQuarterStartMonth() + 2;var quarterStartDate = new Date(nowYear, quarterEndMonth,getMonthDays(quarterEndMonth));return formatDate(quarterStartDate);}js 计算⽉/周的第⼀天和最后⼀天因为项⽬开发中遇到需要向后台传本周的开始和结束时间,以及上⼀周的起⽌时间,就琢磨了半天,总算写出来⼀套,写篇⽂章是为了⽅便⾃⼰记忆,也是分享给需要的⼈,⽔平有限,写的不好请见谅:getDateStr3函数是为了把时间对象转变为yy-mm-dd的字符串,⽅便传值;getWeekStartAndEnd函数是获取周的起⽌时间,并且⽤getDateStr3转换成字符串放到数组中,其中参数0代表当前周,-1代表前⼀周,-2代表上上周,以此类推,反过来也可以1代表下⼀周;getMonthStartAndEnd函数是获取⽉的起⽌时间,传参同上//获取当前⽇期yy-mm-dd//date 为时间对象function getDateStr3(date) {var year = "";var month = "";var day = "";var now = date;year = ""+now.getFullYear();if((now.getMonth()+1)<10){month = "0"+(now.getMonth()+1);}else{month = ""+(now.getMonth()+1);}if((now.getDate())<10){day = "0"+(now.getDate());}else{day = ""+(now.getDate());}return year+"-"+month+"-"+day;}/*** 获得相对当前周AddWeekCount个周的起⽌⽇期* AddWeekCount为0代表当前周为-1代表上⼀个周为1代表下⼀个周以此类推* **/function getWeekStartAndEnd(AddWeekCount) {//起⽌⽇期数组var startStop = new Array();//⼀天的毫秒数var millisecond = 1000 * 60 * 60 * 24;//获取当前时间var currentDate = new Date();//相对于当前⽇期AddWeekCount个周的⽇期currentDate = new Date(currentDate.getTime() + (millisecond * 7*AddWeekCount));//返回date是⼀周中的某⼀天var week = currentDate.getDay();//返回date是⼀个⽉中的某⼀天var month = currentDate.getDate();//减去的天数var minusDay = week != 0 ? week - 1 : 6;//获得当前周的第⼀天var currentWeekFirstDay = new Date(currentDate.getTime() - (millisecond * minusDay)); //获得当前周的最后⼀天var currentWeekLastDay = new Date(currentWeekFirstDay.getTime() + (millisecond * 6)); //添加⾄数组startStop.push(getDateStr3(currentWeekFirstDay));startStop.push(getDateStr3(currentWeekLastDay));return startStop;}/*** 获得相对当⽉AddMonthCount个⽉的起⽌⽇期* AddMonthCount为0 代表当⽉为-1代表上⼀个⽉为1代表下⼀个⽉以此类推* ***/function getMonthStartAndEnd(AddMonthCount) {//起⽌⽇期数组var startStop = new Array();//获取当前时间var currentDate = new Date();var month=currentDate.getMonth()+AddMonthCount;if(month<0){var n = parseInt((-month)/12);month += n*12;currentDate.setFullYear(currentDate.getFullYear()-n);}currentDate = new Date(currentDate.setMonth(month));//获得当前⽉份0-11var currentMonth = currentDate.getMonth();//获得当前年份4位年var currentYear = currentDate.getFullYear();//获得上⼀个⽉的第⼀天var currentMonthFirstDay = new Date(currentYear, currentMonth,1);//获得上⼀⽉的最后⼀天var currentMonthLastDay = new Date(currentYear, currentMonth+1, 0);//添加⾄数组startStop.push(getDateStr3(currentMonthFirstDay));startStop.push(getDateStr3(currentMonthLastDay));//返回return startStop;}好了这篇⽂章就介绍到这了。

java获取当天,前天,明天,本周,本月,本年的开始日期时间和结束日期时间

java获取当天,前天,明天,本周,本月,本年的开始日期时间和结束日期时间

java获取当天,前天,明天,本周,本⽉,本年的开始⽇期时间和结束⽇期时间1package demoone;23import java.sql.Timestamp;4import java.text.ParseException;5import java.text.SimpleDateFormat;6import java.util.ArrayList;7import java.util.Calendar;8import java.util.Date;9import java.util.GregorianCalendar;10import java.util.List;1112public class DateUtils {13//获取当天的开始时间14public static java.util.Date getDayBegin() {15 Calendar cal = new GregorianCalendar();16 cal.set(Calendar.HOUR_OF_DAY, 0);17 cal.set(Calendar.MINUTE, 0);18 cal.set(Calendar.SECOND, 0);19 cal.set(LISECOND, 0);20return cal.getTime();21 }22//获取当天的结束时间23public static java.util.Date getDayEnd() {24 Calendar cal = new GregorianCalendar();25 cal.set(Calendar.HOUR_OF_DAY, 23);26 cal.set(Calendar.MINUTE, 59);27 cal.set(Calendar.SECOND, 59);28return cal.getTime();29 }30//获取昨天的开始时间31public static Date getBeginDayOfYesterday() {32 Calendar cal = new GregorianCalendar();33 cal.setTime(getDayBegin());34 cal.add(Calendar.DAY_OF_MONTH, -1);35return cal.getTime();36 }37//获取昨天的结束时间38public static Date getEndDayOfYesterDay() {39 Calendar cal = new GregorianCalendar();40 cal.setTime(getDayEnd());41 cal.add(Calendar.DAY_OF_MONTH, -1);42return cal.getTime();43 }44//获取明天的开始时间45public static Date getBeginDayOfTomorrow() {46 Calendar cal = new GregorianCalendar();47 cal.setTime(getDayBegin());48 cal.add(Calendar.DAY_OF_MONTH, 1);4950return cal.getTime();51 }52//获取明天的结束时间53public static Date getEndDayOfTomorrow() {54 Calendar cal = new GregorianCalendar();55 cal.setTime(getDayEnd());56 cal.add(Calendar.DAY_OF_MONTH, 1);57return cal.getTime();58 }59//获取本周的开始时间60public static Date getBeginDayOfWeek() {61 Date date = new Date();62if (date == null) {63return null;64 }65 Calendar cal = Calendar.getInstance();66 cal.setTime(date);67int dayofweek = cal.get(Calendar.DAY_OF_WEEK);68if (dayofweek == 1) {69 dayofweek += 7;70 }71 cal.add(Calendar.DATE, 2 - dayofweek);72return getDayStartTime(cal.getTime());73 }74//获取本周的结束时间75public static Date getEndDayOfWeek(){76 Calendar cal = Calendar.getInstance();77 cal.setTime(getBeginDayOfWeek());78 cal.add(Calendar.DAY_OF_WEEK, 6);79 Date weekEndSta = cal.getTime();80return getDayEndTime(weekEndSta);81 }82//获取本⽉的开始时间83public static Date getBeginDayOfMonth() {84 Calendar calendar = Calendar.getInstance();85 calendar.set(getNowYear(), getNowMonth() - 1, 1);86return getDayStartTime(calendar.getTime());87 }88//获取本⽉的结束时间89public static Date getEndDayOfMonth() {90 Calendar calendar = Calendar.getInstance();91 calendar.set(getNowYear(), getNowMonth() - 1, 1);92int day = calendar.getActualMaximum(5);93 calendar.set(getNowYear(), getNowMonth() - 1, day);94return getDayEndTime(calendar.getTime());95 }96//获取本年的开始时间97public static java.util.Date getBeginDayOfYear() {98 Calendar cal = Calendar.getInstance();99 cal.set(Calendar.YEAR, getNowYear());100// cal.set101 cal.set(Calendar.MONTH, Calendar.JANUARY);102 cal.set(Calendar.DATE, 1);103104return getDayStartTime(cal.getTime());105 }106//获取本年的结束时间107public static java.util.Date getEndDayOfYear() {108 Calendar cal = Calendar.getInstance();109 cal.set(Calendar.YEAR, getNowYear());110 cal.set(Calendar.MONTH, Calendar.DECEMBER);111 cal.set(Calendar.DATE, 31);112return getDayEndTime(cal.getTime());113 }114//获取某个⽇期的开始时间115public static Timestamp getDayStartTime(Date d) {116 Calendar calendar = Calendar.getInstance();117if(null != d) calendar.setTime(d);118 calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);119 calendar.set(LISECOND, 0);120return new Timestamp(calendar.getTimeInMillis());121 }122//获取某个⽇期的结束时间123public static Timestamp getDayEndTime(Date d) {124 Calendar calendar = Calendar.getInstance();125if(null != d) calendar.setTime(d);126 calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59); 127 calendar.set(LISECOND, 999);128return new Timestamp(calendar.getTimeInMillis());129 }130//获取今年是哪⼀年131public static Integer getNowYear() {132 Date date = new Date();133 GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();134 gc.setTime(date);135return Integer.valueOf(gc.get(1));136 }137//获取本⽉是哪⼀⽉138public static int getNowMonth() {139 Date date = new Date();140 GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();141 gc.setTime(date);142return gc.get(2) + 1;143 }144//两个⽇期相减得到的天数145public static int getDiffDays(Date beginDate, Date endDate) {146147if (beginDate == null || endDate == null) {148throw new IllegalArgumentException("getDiffDays param is null!");149 }150151long diff = (endDate.getTime() - beginDate.getTime())152 / (1000 * 60 * 60 * 24);153154int days = new Long(diff).intValue();155156return days;157 }158//两个⽇期相减得到的毫秒数159public static long dateDiff(Date beginDate, Date endDate) {160long date1ms = beginDate.getTime();161long date2ms = endDate.getTime();162return date2ms - date1ms;163 }164//获取两个⽇期中的最⼤⽇期165public static Date max(Date beginDate, Date endDate) {166if (beginDate == null) {167return endDate;168 }169if (endDate == null) {170return beginDate;171 }172if (beginDate.after(endDate)) {173return beginDate;174 }175return endDate;176 }177//获取两个⽇期中的最⼩⽇期178public static Date min(Date beginDate, Date endDate) {179if (beginDate == null) {180return endDate;181 }182if (endDate == null) {183return beginDate;184 }185if (beginDate.after(endDate)) {186return endDate;187 }188return beginDate;189 }190//返回某⽉该季度的第⼀个⽉191public static Date getFirstSeasonDate(Date date) {192final int[] SEASON = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4 };193 Calendar cal = Calendar.getInstance();194 cal.setTime(date);195int sean = SEASON[cal.get(Calendar.MONTH)];196 cal.set(Calendar.MONTH, sean * 3 - 3);197return cal.getTime();198 }199//返回某个⽇期下⼏天的⽇期200public static Date getNextDay(Date date, int i) {201 Calendar cal = new GregorianCalendar();202 cal.setTime(date);203 cal.set(Calendar.DATE, cal.get(Calendar.DATE) + i);204return cal.getTime();205 }206//返回某个⽇期前⼏天的⽇期207public static Date getFrontDay(Date date, int i) {208 Calendar cal = new GregorianCalendar();209 cal.setTime(date);210 cal.set(Calendar.DATE, cal.get(Calendar.DATE) - i);211return cal.getTime();212 }213//获取某年某⽉到某年某⽉按天的切⽚⽇期集合(间隔天数的⽇期集合)214public static List getTimeList(int beginYear, int beginMonth, int endYear, 215int endMonth, int k) {216 List list = new ArrayList();217if (beginYear == endYear) {218for (int j = beginMonth; j <= endMonth; j++) {219 list.add(getTimeList(beginYear, j, k));220221 }222 } else {223 {224for (int j = beginMonth; j < 12; j++) {225 list.add(getTimeList(beginYear, j, k));226 }227228for (int i = beginYear + 1; i < endYear; i++) {229for (int j = 0; j < 12; j++) {230 list.add(getTimeList(i, j, k));231 }232 }233for (int j = 0; j <= endMonth; j++) {234 list.add(getTimeList(endYear, j, k));235 }236 }237 }238return list;239 }240//获取某年某⽉按天切⽚⽇期集合(某个⽉间隔多少天的⽇期集合)241public static List getTimeList(int beginYear, int beginMonth, int k) {242 List list = new ArrayList();243 Calendar begincal = new GregorianCalendar(beginYear, beginMonth, 1); 244int max = begincal.getActualMaximum(Calendar.DATE);245for (int i = 1; i < max; i = i + k) {246 list.add(begincal.getTime());247 begincal.add(Calendar.DATE, k);248 }249 begincal = new GregorianCalendar(beginYear, beginMonth, max);250 list.add(begincal.getTime());251return list;252 }253 }1//获取某年某⽉的第⼀天⽇期2public static Date getStartMonthDate(int year, int month) {3 Calendar calendar = Calendar.getInstance();4 calendar.set(year, month - 1, 1);5return calendar.getTime();6 }78//获取某年某⽉的最后⼀天⽇期9public static Date getEndMonthDate(int year, int month) {10 Calendar calendar = Calendar.getInstance();11 calendar.set(year, month - 1, 1);12int day = calendar.getActualMaximum(5);13 calendar.set(year, month - 1, day);14return calendar.getTime();15 }DateUtils。

js获取本日、本周、本月的时间代码

js获取本日、本周、本月的时间代码

js获取本⽇、本周、本⽉的时间代码本⽇时间function showToDay(){var Nowdate=new Date();M=Number(Nowdate.getMonth())+1alert(Nowdate.getMonth()+"⽉,"+Nowdate.getDate()+"号,星期"+Nowdate.getDay());return Nowdate.getYear()+"-"+M+"-"+Nowdate.getDate();}昨天function showTomorrow(){var tom=new Date();tom.setDate(tom.getDate()+1);M=Number(tom.getMonth())+1return tom.getYear()+"-"+M+"-"+tom.getDate();}本周第⼀天function showWeekFirstDay(){var Nowdate=new Date();var WeekFirstDay=new Date(Nowdate-(Nowdate.getDay()-1)*86400000);M=Number(WeekFirstDay.getMonth())+1return WeekFirstDay.getYear()+"-"+M+"-"+WeekFirstDay.getDate();}本周最后天function showWeekLastDay(){var Nowdate=new Date();var WeekFirstDay=new Date(Nowdate-(Nowdate.getDay()-1)*86400000);var WeekLastDay=new Date((WeekFirstDay/1000+6*86400)*1000);M=Number(WeekLastDay.getMonth())+1return WeekLastDay.getYear()+"-"+M+"-"+WeekLastDay.getDate();}本⽉第⼀天function showMonthFirstDay(){var Nowdate=new Date();var MonthFirstDay=new Date(Nowdate.getYear(),Nowdate.getMonth(),1);M=Number(MonthFirstDay.getMonth())+1return MonthFirstDay.getYear()+"-"+M+"-"+MonthFirstDay.getDate();}本⽉最后⼀天function showMonthLastDay(){var Nowdate=new Date();var MonthNextFirstDay=new Date(Nowdate.getYear(),Nowdate.getMonth()+1,1);var MonthLastDay=new Date(MonthNextFirstDay-86400000);M=Number(MonthLastDay.getMonth())+1return MonthLastDay.getYear()+"-"+M+"-"+MonthLastDay.getDate();}function getTime(s){var time1=document.getElementById("num1");var time2=document.getElementById("num2");if(s==1){//本⽇时间time1.value=showToDay();//alert("今⽇:"+time1.value);time2.value=showTomorrow();//alert("今⽇:"+time2.value);}else if(s==2){//本周时间time1.value=showWeekFirstDay();//alert("本⽉第⼀天:"+time1.value);time2.value=showWeekLastDay();//alert("本⽉最后⼀天:"+time2.value);}else{//本⽉时间time1.value=showMonthFirstDay();//alert("本⽉第⼀天"+time1.value);time2.value=showMonthLastDay();//alert("本⽉最后⼀天"+time2.value);}}其他⽹友补充的完整测试代码<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><input type="text" id="dateFrom" value=""><input type="text" id="dateTo" value=""><script>window.onload = function() {// getDate("thisDay");// getDate("thisWeek");// getDate("thisMonth");getDate("thisYear");}//获取推送时间段function getDate(type){var kssj,jssj;var today = new Date();var DAY = 1000*60*60*24;if(type =="thisDay") { //当天kssj = new Date();jssj = new Date();}if(type == "thisWeek") { //本周周kssj = getThisWeekFirstDay();//本周第⼀天jssj = new Date();}if(type == "thisMonth") { //本⽉kssj = getThisMonthFirstDay();//本⽉第⼀天jssj = new Date();}if(type == "thisYear") {kssj = getThisYearFirstDay();//本年第⼀天jssj = new Date();}var dateFrom = kssj.format('yyyy-MM-dd');var dateTo = jssj.format('yyyy-MM-dd');document.getElementById("dateFrom").value=dateFrom;document.getElementById("dateTo").value=dateTo;}function getThisWeekFirstDay() {var now = new Date();var day = now.getDay();var week = "1234567";var first = 0 - week.indexOf(day);var thisWeekfirstDay = new Date;thisWeekfirstDay.setDate (thisWeekfirstDay.getDate () + first); return thisWeekfirstDay;}function getThisMonthFirstDay(){var date=new Date();date.setDate(1);return date;}function getThisYearFirstDay() {var currentDate=new Date();var currentYear=currentDate.getFullYear();var currentYearFirstDate=new Date(currentYear,0,1);return currentYearFirstDate;}//data类型转stringDate.prototype.format = function(format){var o = {"M+" : this.getMonth()+1, //month"d+" : this.getDate(), //day"h+" : this.getHours(), //hour"m+" : this.getMinutes(), //minute"s+" : this.getSeconds(), //second"q+" : Math.floor((this.getMonth()+3)/3), //quarter"S" : this.getMilliseconds() //millisecond}if(/(y+)/.test(format)) format=format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); for(var k in o)if(new RegExp("("+ k +")").test(format)) format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] :("00"+ o[k]).substr((""+ o[k]).length));return format;}</script></body></html>这样基本上就解决问题了。

MYSQL获取当前年、季、月、周第一天、最后一天的日期时间戳

MYSQL获取当前年、季、月、周第一天、最后一天的日期时间戳

MYSQL获取当前年、季、⽉、周第⼀天、最后⼀天的⽇期时间戳 因为做⼀些商场某个会员今年的消费分析,所以对sql中时间的获取进⾏了判断。

 例如获取今年(即当前年的第⼀天到昨天0时之间)的消费总额。

 如果需要时间戳转换,⽤UNIX_TIMESTAMP()函数。

 ⼀、下⾯是⼀些mysql的时间获取语句:#当年第⼀天:SELECT DATE_SUB(CURDATE(),INTERVAL dayofyear(now())-1DAY);#当年最后⼀天:SELECT concat(YEAR(now()),'-12-31');#当前week的第⼀天:select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) +1DAY);#当前week的最后⼀天:select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) -5DAY);#前⼀week的第⼀天:select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) +8DAY);#前⼀week的最后⼀天:select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) +2DAY);#前两week的第⼀天:select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) +15DAY);#前两week的最后⼀天:select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) +9DAY);#当前month的第⼀天:SELECT concat(date_format(LAST_DAY(now()),'%Y-%m-'),'01');#当前month的最后⼀天:SELECT LAST_DAY(now());#前⼀month的第⼀天:SELECT concat(date_format(LAST_DAY(now() - interval 1month),'%Y-%m-'),'01');#前⼀month的最后⼀天:SELECT LAST_DAY(now() - interval 1month);#前两month的第⼀天:SELECT concat(date_format(LAST_DAY(now() - interval 2month),'%Y-%m-'),'01');#前两month的最后⼀天:SELECT LAST_DAY(now() - interval 2month);#当前quarter的第⼀天:select concat(date_format(LAST_DAY(MAKEDATE(EXTRACT(YEAR FROM CURDATE()),1) + interval QUARTER(CURDATE())*3-3month),'%Y-%m-'),'01');#当前quarter的最后⼀天:select LAST_DAY(MAKEDATE(EXTRACT(YEAR FROM CURDATE()),1) + interval QUARTER(CURDATE())*3-1month);#前⼀quarter的第⼀天:select concat(date_format(LAST_DAY(MAKEDATE(EXTRACT(YEAR FROM CURDATE()),1) + interval QUARTER(CURDATE())*3-6month),'%Y-%m-'),'01');#前⼀quarter的最后⼀天:select LAST_DAY(MAKEDATE(EXTRACT(YEAR FROM CURDATE()),1) + interval QUARTER(CURDATE())*3-4month);#前两quarter的第⼀天:select concat(date_format(LAST_DAY(MAKEDATE(EXTRACT(YEAR FROM CURDATE()),1) + interval QUARTER(CURDATE())*3-9month),'%Y-%m-'),'01');#前两quarter的最后⼀天:select LAST_DAY(MAKEDATE(EXTRACT(YEAR FROM CURDATE()),1) + interval QUARTER(CURDATE())*3-7month);⼆、举⼏个某会员的消费分析的sql语句:-- 今年的消费总额SELECT IFNULL(SUM(a.trade_amount)/100,0)FROM mob_checkout_counter.checkout_record a -- 消费记录表WHERE card_code ='某会员的标识'AND checkout_status = ‘消费状态’AND trade_time >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(),INTERVAL dayofyear(now())-1DAY)) -- 当前年的第⼀天的时间戳AND trade_time <= UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE) - INTERVAL 1DAY) -- 昨天的0时的时间戳-- 今年的消费笔数SELECT COUNT(*)FROM mob_checkout_counter.checkout_record aWHERE card_code ='2396998881100009965'AND checkout_status =1AND trade_time >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(),INTERVAL dayofyear(now())-1DAY))AND trade_time <= UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE) - INTERVAL 1DAY)-- 今年的客单价SELECT IFNULL(SUM(a.trade_amount)/100,0)/COUNT(*)FROM mob_checkout_counter.checkout_record aWHERE card_code ='2396998881100009965'AND checkout_status =1AND trade_time >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(),INTERVAL dayofyear(now())-1DAY))AND trade_time <= UNIX_TIMESTAMP(CAST(SYSDATE()AS DATE) - INTERVAL 1DAY)。

sql语句获取今天、昨天、近7天、本周、上周、本月、上月、半年数据

sql语句获取今天、昨天、近7天、本周、上周、本月、上月、半年数据

sql语句获取今天、昨天、近7天、本周、上周、本⽉、上⽉、半年数据01话说有⼀⽂章表article,存储⽂章的添加⽂章的时间是add_time字段,该字段为int(5)类型的,现需要查询今天添加的⽂章总数并且按照时间从⼤到⼩排序,则查询语句如下:02031select * from `article` where date_format(from_UNIXTIME(`add_time`),'%Y-%m-%d') = date_format(now(),'%Y-%m-%d');04或者:05061select * from `article` where to_days(date_format(from_UNIXTIME(`add_time`),'%Y-%m-%d')) = to_days(now());07假设以上表的add_time字段的存储类型是DATETIME类型或者TIMESTAMP类型,则查询语句也可按如下写法:0809查询今天的信息记录:10111select * from `article` where to_days(`add_time`) = to_days(now());12查询昨天的信息记录:13141select * from `article` where to_days(now()) – to_days(`add_time`) <= 1;15查询近7天的信息记录:16171select * from `article` where date_sub(curdate(), INTERVAL 7 DAY) <= date(`add_time`);18查询近30天的信息记录:19201select * from `article` where date_sub(curdate(), INTERVAL 30 DAY) <= date(`add_time`);21查询本⽉的信息记录:22231select * from `article` where date_format(`add_time`, ‘%Y%m') = date_format(curdate() , ‘%Y%m');24查询上⼀⽉的信息记录:25261select * from `article` where period_diff(date_format(now() , ‘%Y%m') , date_format(`add_time`, ‘%Y%m')) =1;27对上⾯的SQL语句中的⼏个函数做⼀下分析:2829(1)to_days3031就像它的名字⼀样,它是将具体的某⼀个⽇期或时间字符串转换到某⼀天所对应的unix时间戳,如:323301 mysql> select to_days('2010-11-22 14:39:51');3402 +--------------------------------+3503 | to_days('2010-11-22 14:39:51') |3604 +--------------------------------+3705 | 734463 |3806 +--------------------------------+39074008 mysql> select to_days('2010-11-23 14:39:51');4109 +--------------------------------+4210 | to_days('2010-11-23 14:39:51') |4311 +--------------------------------+4412 | 734464 |4513 +--------------------------------+46可以看出22⽇与23⽇的差别就是,转换之后的数增加了1,这个粒度的查询是⽐较粗糙的,有时可能不能满⾜我们的查询要求,那么就需要使⽤细粒度的查询⽅法str_to_date函数了,下⾯将分析这个函数的⽤法。

时间戳生成的方法

时间戳生成的方法

时间戳生成的方法一、时间戳是什么?1.1 时间戳啊,简单来说就是一个能表示某个特定时刻的标记。

就像我们生活里给某个重要事件打个标记一样,在计算机的世界里,时间戳就是标记某个瞬间的数字。

它精确到啥程度呢?可以精确到毫秒甚至更小的单位呢。

比如说,你在网上下单买东西,系统就会记录下这个下单动作发生的准确时间,这个时间就是以时间戳的形式存在的。

1.2 这时间戳可重要啦,它就像一个时间的证人。

在很多数据处理、网络通信的场景里,没有它可不行。

它能让我们清楚地知道事情发生的先后顺序,就像排队的时候,谁先谁后一目了然。

二、时间戳生成的常见方法。

2.1 系统时钟法。

- 这是最基本的一种方法。

计算机系统本身有个时钟,这个时钟一直在滴答滴答地走。

当需要生成时间戳的时候,就直接从这个系统时钟里读取当前的时间信息。

就好比我们看墙上的时钟来确定现在是什么时候一样。

不过呢,这种方法也有点小问题。

要是系统时钟不准了,那生成的时间戳可就有偏差了。

就像你戴了个走得不准的表,看时间肯定会出错。

2.2 网络时间协议(NTP)法。

- 这是个比较靠谱的方法。

很多设备会通过网络时间协议来同步时间。

就像大家都听一个标准的报时钟一样。

设备会连接到专门的时间服务器,从那里获取准确的时间信息,然后生成时间戳。

这样一来,即使本地系统时钟有点小毛病,也能得到比较准确的时间戳。

这就好比大家都按照电视台的标准时间来对表,不容易出错。

2.3 特定算法生成法。

- 有些时候,为了满足特殊的需求,会用特定的算法来生成时间戳。

比如说在一些加密场景下,会把当前时间和一些密钥之类的东西通过算法混合起来,生成一个独特的时间戳。

这就像是给时间戳穿上了一件加密的外衣,只有知道算法和相关密钥的才能解读它。

这种方法虽然复杂一点,但安全性很高,就像给宝贝上了一把牢固的锁。

三、时间戳生成的注意事项。

3.1 准确性。

- 生成时间戳的时候,准确性那是首要的。

要是时间戳不准,就像盖房子地基没打好一样。

如何获取本周本月本日的开始时间和结束时间的时间戳

如何获取本周本月本日的开始时间和结束时间的时间戳

如何获取本周本月本日的开始时间和结束时间的时间戳要获取本周、本月和本日的开始时间和结束时间的时间戳,可以使用编程语言中的日期和时间函数来实现。

以下是一种常见的方法来获取这些时间戳的示例(使用Python语言):
获取本周的开始时间和结束时间的时间戳:
```
```
获取本月的开始时间和结束时间的时间戳:
```
start_of_month = today.replace(day=1)
end_of_month =
start_of_month.replace(day=calendar.monthrange(start_of_month.ye ar, start_of_month.month)[1])
```
获取本日的开始时间和结束时间的时间戳:
```
```
请注意,这些示例中使用的是当前本地时间。

如果需要处理不同时区的时间,你可能需要使用额外的函数来设置或转换时区。

具体的方法可能因不同的编程语言和库而有所差异。

php获取指定月份的开始结束时间戳

php获取指定月份的开始结束时间戳
}
/**
* 获取指定时间戳所在的月份的开始时间戳和结束时间戳
*
* @param int $timestamp
* @return array(开始时间,结束时间)
*/
function getMonthBeginAndEnd($timestamp = 0) {
$timestamp = $timestamp ? $timestamp : time();
$year = date('Y', $timestamp);
$month = date('m', $timestamp);
$d = date('t', strtotime($year . '-' . $month));
return ['begin' => strtotime($year . '-' . $month), 'end' => mktime(23, 59, 59, $month, $d, $year)];
获取指定时间戳所在的月份的开始时间戳和结束时间戳paraminttimestampreturnarray开始时间结束时间functiongetmonthbeginandendtimestamp0timestamptimestamp
php获取指定月份的开始结束时间戳
php 获取指定月份的开始结束时间戳。
<?php
/**
*
* 获取指定年月的开始和结束时间戳
*
* @param int $year 年份
* @param intay(开始时间,结束时间)
*/
function getMonthBeginAndEnd($year = 0, $month = 0) {

Shell脚本编写的窍门如何处理日期和时间操作

Shell脚本编写的窍门如何处理日期和时间操作

Shell脚本编写的窍门如何处理日期和时间操作Shell脚本编写的窍门:如何处理日期和时间操作在Shell脚本中,经常需要对日期和时间进行处理,比如获取当前时间、计算时间差、格式化输出等。

下面将介绍一些有用的技巧和方法,帮助你更好地处理日期和时间操作。

一、获取当前日期和时间在Shell脚本中,我们可以使用date命令来获取当前日期和时间。

具体使用如下:```shellcurrent_date=$(date +%Y-%m-%d) # 获取当前日期,格式为YYYY-MM-DDcurrent_time=$(date +%H:%M:%S) # 获取当前时间,格式为HH:MM:SS```二、计算时间差有时候我们需要计算两个日期或时间之间的差值,比如计算某个操作执行的时间。

Shell中可以使用date命令和时间戳来实现。

```shellstart_time=$(date +%s) # 获取开始时间的时间戳# 执行一些需要计时的操作end_time=$(date +%s) # 获取结束时间的时间戳time_diff=$((end_time - start_time)) # 计算时间差,单位为秒echo "操作执行时间为:$time_diff 秒"```三、格式化输出日期和时间有时候我们需要自定义日期和时间的输出格式,比如将日期格式化为"YYYY年MM月DD日"。

在Shell中,我们可以使用date命令的"-d"参数来实现。

```shell# 获取当前日期current_date=$(date +%Y-%m-%d)# 格式化输出为"YYYY年MM月DD日"formatted_date=$(date -d "$current_date" "+%Y年%m月%d日")echo "当前日期为:$formatted_date"```四、时间和日期的加减运算在Shell中,我们可以使用date命令进行时间和日期的加减运算。

java获取时间戳的方法

java获取时间戳的方法

java获取时间戳的方法Java中时间戳的概念,就是把当前的时间和日期换算成一串数字。

这些数字通常用来标记特定的时间,在特定的历史时期内都能够依照统一的规则,精确地表示出来。

时间戳比较常见的展示形式主要有十六进制和十进制两种,在不同的操作系统和数据库中,采用的时间戳的形式也可能有所不同。

在Java编程语言中,可以使用以下几种方法来获取时间戳:(1)使用System类的currentTimeMillis()方法:currentTimeMillis()是System类的一个静态方法,可以返回从1970年1月1日00:00:00GMT+00:00(即格林尼治标准时间)开始计算,到当前系统时间所经过的毫秒数。

下面是使用currentTimeMillis()方法获取当前时间戳的代码示例:long timeStamp = System.currentTimeMillis();(2)使用java.util.Date类的getTime()方法:Date类有一个getTime()方法,可以获取Date对象中封装的毫秒级时间戳。

下面是使用getTime()方法获取当前时间戳的代码示例:long timeStamp = new Date().getTime();(3)使用java.time.Instant类的toEpochMilli()方法:Instant类有一个toEpochMilli()方法,可以获取该Instant对象的毫秒数,这个毫秒数就是从1970年1月1日凌晨00:00:00开始计算,到当前Instant对象表示的时间点所经过的毫秒数。

下面是使用toEpochMilli()方法获取当前时间戳的代码示例: long timeStamp = Instant.now().toEpochMilli();(4)使用java.time.LocalDateTime类的toInstant()方法: LocalDateTime类继承自java.time.temporal.Temporal,有一个toInstant()的方法,可以将LocalDateTime类的实例转换成Instant类的实例,然后再利用Instant类的toEpochMilli()方法获取时间戳。

获取年月日的方法

获取年月日的方法

获取年月日的方法要获取当前的年月日,可以使用以下几种方法:1.使用time模块获取当前时间戳:```pythonimport timetimestamp = time.time() #获取当前时间戳date = time.localtime(timestamp) #将时间戳转换为本地时间year = date.tm_year #获取年份month = date.tm_mon #获取月份day = date.tm_mday #获取日期print(year, month, day) #打印年月日```2.使用datetime模块获取当前日期:```pythonfrom datetime import datetimenow = datetime.now() #获取当前日期时间year = now.year #获取年份month = now.month #获取月份day = now.day #获取日期print(year, month, day) #打印年月日```3.使用calendar模块获取当前日期:```pythonimport calendaryear = calendar.datetime.datetime.now().year #获取年份month = calendar.datetime.datetime.now().month #获取月份day = calendar.datetime.datetime.now().day #获取日期print(year, month, day) #打印年月日```4.使用date模块获取当前日期:```pythonfrom datetime import datetoday = date.today() #获取当前日期year = today.year #获取年份month = today.month #获取月份day = today.day #获取日期print(year, month, day) #打印年月日```5.使用strftime()方法格式化日期:```pythonimport timetimestamp = time.time() #获取当前时间戳formatted_date = time.strftime('%Y-%m-%d',time.localtime(timestamp)) #格式化为年月日形式print(formatted_date) #打印年月日```6.使用字符串截取方法获取年月日:```pythonimport timetimestamp = time.ctime() #获取当前时间的字符串形式,如"Tue Oct 10 09:00:00 2023"formatted_date = timestamp[:10] #截取年月日部分print(formatted_date) #打印年月日```这些方法可以灵活地根据需求选择使用。

Java获取当天、当前月、当前年(今年)的开始和结束时间戳

Java获取当天、当前月、当前年(今年)的开始和结束时间戳

Java获取当天、当前⽉、当前年(今年)的开始和结束时间戳最近在做统计相关的功能的时候涉及到了获取当天的开始和结束的时间戳、当⽉和当年的开始结束时间戳,特此记录,以作备忘。

相关代码package com.lingyejun.authenticator;import java.time.Instant;import java.time.LocalDateTime;import java.time.ZoneId;import java.util.Calendar;import java.util.TimeZone;public class CalendarAdjust {/*** 获取指定某⼀天的开始时间戳** @param timeStamp 毫秒级时间戳* @param timeZone 如 GMT+8:00* @return*/public static Long getDailyStartTime(Long timeStamp, String timeZone) {Calendar calendar = Calendar.getInstance();calendar.setTimeZone(TimeZone.getTimeZone(timeZone));calendar.setTimeInMillis(timeStamp);calendar.set(Calendar.HOUR_OF_DAY, 0);calendar.set(Calendar.SECOND, 0);calendar.set(Calendar.MINUTE, 0);calendar.set(LISECOND, 0);return calendar.getTimeInMillis();}/*** 获取指定某⼀天的结束时间戳** @param timeStamp 毫秒级时间戳* @param timeZone 如 GMT+8:00* @return*/public static Long getDailyEndTime(Long timeStamp, String timeZone) {Calendar calendar = Calendar.getInstance();calendar.setTimeZone(TimeZone.getTimeZone(timeZone));calendar.setTimeInMillis(timeStamp);calendar.set(Calendar.HOUR_OF_DAY, 23);calendar.set(Calendar.MINUTE, 59);calendar.set(Calendar.SECOND, 59);calendar.set(LISECOND, 999);return calendar.getTimeInMillis();}/*** 获取当⽉开始时间戳** @param timeStamp 毫秒级时间戳* @param timeZone 如 GMT+8:00* @return*/public static Long getMonthStartTime(Long timeStamp, String timeZone) {Calendar calendar = Calendar.getInstance();// 获取当前⽇期calendar.setTimeZone(TimeZone.getTimeZone(timeZone));calendar.setTimeInMillis(timeStamp);calendar.add(Calendar.YEAR, 0);calendar.add(Calendar.MONTH, 0);calendar.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前⽇期既为本⽉第⼀天calendar.set(Calendar.HOUR_OF_DAY, 0);calendar.set(Calendar.MINUTE, 0);calendar.set(Calendar.SECOND, 0);calendar.set(LISECOND, 0);return calendar.getTimeInMillis();}/*** 获取当⽉的结束时间戳** @param timeStamp 毫秒级时间戳* @param timeZone 如 GMT+8:00* @return*/public static Long getMonthEndTime(Long timeStamp, String timeZone) {Calendar calendar = Calendar.getInstance();// 获取当前⽇期calendar.setTimeZone(TimeZone.getTimeZone(timeZone));calendar.setTimeInMillis(timeStamp);calendar.add(Calendar.YEAR, 0);calendar.add(Calendar.MONTH, 0);calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));// 获取当前⽉最后⼀天calendar.set(Calendar.HOUR_OF_DAY, 23);calendar.set(Calendar.MINUTE, 59);calendar.set(Calendar.SECOND, 59);calendar.set(LISECOND, 999);return calendar.getTimeInMillis();}/*** 获取当年的开始时间戳** @param timeStamp 毫秒级时间戳* @param timeZone 如 GMT+8:00* @return*/public static Long getYearStartTime(Long timeStamp, String timeZone) {Calendar calendar = Calendar.getInstance();// 获取当前⽇期calendar.setTimeZone(TimeZone.getTimeZone(timeZone));calendar.setTimeInMillis(timeStamp);calendar.add(Calendar.YEAR, 0);calendar.add(Calendar.DATE, 0);calendar.add(Calendar.MONTH, 0);calendar.set(Calendar.DAY_OF_YEAR, 1);calendar.set(Calendar.HOUR_OF_DAY, 0);calendar.set(Calendar.MINUTE, 0);calendar.set(Calendar.SECOND, 0);calendar.set(LISECOND, 0);return calendar.getTimeInMillis();}/*** 获取当年的最后时间戳** @param timeStamp 毫秒级时间戳* @param timeZone 如 GMT+8:00* @return*/public static Long getYearEndTime(Long timeStamp, String timeZone) {Calendar calendar = Calendar.getInstance();// 获取当前⽇期calendar.setTimeZone(TimeZone.getTimeZone(timeZone));calendar.setTimeInMillis(timeStamp);int year = calendar.get(Calendar.YEAR);calendar.clear();calendar.set(Calendar.YEAR, year);calendar.set(Calendar.HOUR_OF_DAY, 23);calendar.set(Calendar.MINUTE, 59);calendar.set(Calendar.SECOND, 59);calendar.set(LISECOND, 999);calendar.roll(Calendar.DAY_OF_YEAR, -1);return calendar.getTimeInMillis();}/*** 时间戳转字符串** @param timestamp 毫秒级时间戳* @param zoneId 如 GMT+8或UTC+08:00* @return*/public static String timestampToStr(long timestamp, String zoneId) {ZoneId timezone = ZoneId.of(zoneId);LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), timezone);return localDateTime.toString();}public static void main(String[] args) {Long currentTime = System.currentTimeMillis();System.out.println("Current Time : " + currentTime + " = " + timestampToStr(currentTime, "GMT+8"));Long dailyStart = getDailyStartTime(currentTime, "GMT+8:00");Long dailyEnd = getDailyEndTime(currentTime, "GMT+8:00");Long monthStart = getMonthStartTime(currentTime, "GMT+8:00");Long monthEnd = getMonthEndTime(currentTime, "GMT+8:00");Long yearStart = getYearStartTime(currentTime, "GMT+8:00");Long yearEnd = getYearEndTime(currentTime, "GMT+8:00");System.out.println("Daily Start : " + dailyStart + " = " + timestampToStr(dailyStart, "GMT+8") + " Daily End : " + dailyEnd + " = " + timestampToStr(dailyEnd, "GMT+8"));System.out.println("Month Start : " + monthStart + " = " + timestampToStr(monthStart, "GMT+8") + " Month End : " + monthEnd + " = " + timestampToStr(monthEnd, "GMT+8")); System.out.println("Year Start : " + yearStart + " = " + timestampToStr(yearStart, "GMT+8") + " Year End : " + yearEnd + " = " + timestampToStr(yearEnd, "GMT+8"));}}效果。

获取每天时间戳,每周时间戳,每月时间戳和每年时间戳

获取每天时间戳,每周时间戳,每月时间戳和每年时间戳

获取每天时间戳,每周时间戳,每⽉时间戳和每年时间戳只是⼀个思路,后⾯还会不断的优化,如果您有更好的⽅法和思路请在评论中写出,我会及时更新并标注来源封装的⽅法<?php/*** 得到对应的时间戳* @method getTime* deep* @param [string] $year [年份]* @param [string] $month [⽉份]* @return [array] ['YearDay','MonthDay','normalWeek','week','month'] [时间戳]*/function getTime($year,$month){$monthNumber = $month;$month = sprintf("%02d", intval($month));$year = str_pad(intval($year), 4, "0", STR_PAD_RIGHT);$month>12 || $month<1 ? $month=1 : $month=$month;$start = strtotime($year . $month . "01000000");$startstr = date("Y-m-01", $start);$end = strtotime(date('Y-m-d 23:59:59', strtotime("$startstr +6 day")));$Monthend = strtotime(date('Y-m-d 23:59:59', strtotime("$startstr +1 month -1 day")));$days = date('t',$start);//天(每年中每天的开始和结束)$time = mktime(21,21,21,2,1,$year);$yearDays = date('t',$time)==29?'366':'365';$YearDay['1']['start'] = strtotime($year . '-01-01 00:00:00');$YearDay['1']['end'] = $YearDay['1']['start']+86399;for ($i=2; $i <=$yearDays ; $i++) {$YearDay[$i]['start'] = $YearDay[$i - 1]['end'] + 1;$YearDay[$i]['end'] = $YearDay[$i - 1]['end'] + 86400;}//天(每⽉每天的开始和结束)$MonthDay['1']['start'] = $start;$MonthDay['1']['end'] = $MonthDay['1']['start']+86399;for ($i=2; $i <= $days ; $i++) {$MonthDay[$i]['start'] = $MonthDay[$i - 1]['end'] + 1;$MonthDay[$i]['end'] = $MonthDay[$i - 1]['end'] + 86400;}//天(倒退30天的开始和结束)$backDays = [];for($i=0;$i<=30;$i++){$backDays[$i]['start']=strtotime(date("Y-m-d 00:00:00",strtotime('-'.$i.'day')));$backDays[$i]['end']=strtotime(date("Y-m-d 23:59:59",strtotime('-'.$i.'day')));}asort($backDays);//周(将⼀个⽉以每七天为⼀周划分的开始和结束)$num = ceil($days/7);$weekSeven['1']['start'] = $start;$weekSeven['1']['end'] = $end;for ($i=2; $i <= $num ; $i++) {$weekSeven[$i]['start'] = $weekSeven[$i - 1]['end'] + 1;$weekSeven[$i]['end'] = $weekSeven[$i - 1]['end'] + 604800;}$weekSeven[count($weekSeven)]['end'] = $Monthend;//周(⼀个⽉按正常的每周划分)$time = $year . '-' . $month;$weekday = date('w', strtotime($time));if ($weekday == 1) { //1号是周⼀$firstWeekDay = 7;} elseif ($weekday == 0) { //1号是周⽇$firstWeekDay = 1;} else {$firstWeekDay = 8 - $weekday;}$endThisweek = mktime(23, 59, 59, $month, $firstWeekDay, $year);$weekArray[1] = [strtotime($time), $endThisweek];$weeknum = 1 + ceil((date('t', $month) - $firstWeekDay) / 7); //获取到本⽉⼀共有⼏周$beginThisWeek = mktime(0, 0, 0, $month, $firstWeekDay + 1, $year);$endThisweek = mktime(23, 59, 59, $month, $firstWeekDay + 7, $year);for ($i = 2; $i <= $weeknum; $i++) {$weekArray[$i] = [($beginThisWeek + ($i - 2) * 7 * 86400), ($endThisweek + ($i - 2) * 7 * 86400)];}//获取每周的时间节点$weekArray[$weeknum] = [$weekArray[$weeknum][0], mktime(23, 59, 59, $month, date('t', strtotime($time)), $year)];//周(每年的正常周)$yearFirstDay = $year.'-01-01 00:00:00';$yearEndDay = $year.'-12-31 23:59:59';$week = date('N',strtotime($yearFirstDay));//当年第⼀周的开始时间和结束时间(开始时间不⼀定是星期⼀)$days = 8-$week;$firstWeekendDay = date('Y-m-d H:i:s',strtotime($year.'-01-0'.$days.' 23:59:59'));$weeks = [];$weeks[1]['start'] = strtotime($yearFirstDay);$weeks[1]['end'] = strtotime($year.'-01-0'.$days.' 23:59:59');//组装⼀年中完整的各周开始和结束时间戳$days2 = ((strtotime($yearEndDay)-$weeks[1]['end'])/86400)/7;$days3 = (int)floor($days2);$length = $days3+1;for($i=2;$i<=$length;$i++) {$weeks[$i]['start'] = 1+$weeks[$i-1]['end'];$weeks[$i]['end'] = 604800+$weeks[$i-1]['end'];}//组装最后⼀周的开始和结束时间$remainder = ((strtotime($yearEndDay)-$weeks[1]['end'])/86400)%7;if($remainder > 0) {$data = array();$data['start'] = 1+end($weeks)['end'];$data['end'] = ($remainder*86400)+end($weeks)['end'];array_push($weeks,$data);}//每⽉(每年中每⽉的开始和结束)$month = [];for ($i = 1; $i <= 12; $i++) {$mon = sprintf("%02d", intval($i));$mon > 12 || $mon < 1 ? $mon = 1 : $mon = $mon;$mStart = strtotime($year . $mon . "01000000");$mStartCode = date("Y-m-01", $mStart);$mEnd = strtotime(date('Y-m-d 23:59:59', strtotime("$mStartCode +1 month -1 day")));$month[$i]['start'] = $mStart;$month[$i]['end'] = $mEnd;}return ['yearDay'=>$YearDay,'monthDay'=>$MonthDay,'backDay'=>$backDays,'normalWeek'=>$weekArray,'weekSeven'=>$weekSeven,'yearWeek'=>$weeks }获取时间范围内的时间戳 七天⼀周/30天⼀个⽉<?php/** @Author: wyy* @Date: 2018-12-16 20:32:47* @Email: 2752154874@* @Last Modified by: wyy* @Last Modified time: 2018-12-16 21:38:48*//*** 得到对应的时间戳* @method getRangTime* deep* @param [int] $start [开始时间戳]* @param [int] $end [结束时间戳]* @param array $data [时间戳]* @param string $mark [标识符]* @return [array] $data [指定的时间戳]*/function getRangTime($start,$end,$data=[],$mark='d'){$data[] = $start;if($start<$end){if ($mark == 'd') {$data = getRangTime($start+60*60*24,$end,$data,$mark);} elseif ($mark == 'w') {$data = getRangTime($start+60*60*24*7,$end,$data,$mark); } elseif ($mark == 'm') {$data = getRangTime($start+60*60*24*30,$end,$data,$mark); } elseif ($mark == 'y') {$data = getRangTime($start+60*60*24*365,$end,$data,$mark); }}return$data;}单独的⽅法/*** 每年的每天* @method getYearDay* deep* @param [string] $year [年]* @return [array] $day [每年的每天的开始和结束]*/function getYearDay($year){//判断是否为闰年$time = mktime(21,21,21,2,1,$year);$yearDays = date('t',$time)==29?'366':'365';$day = [];$day['1']['start'] = strtotime($year . '-01-01 00:00:00');$day['1']['end'] = $day['1']['start']+86399;for ($i=2; $i <=$yearDays ; $i++) {$day[$i]['start'] = $day[$i - 1]['end'] + 1;$day[$i]['end'] = $day[$i - 1]['end'] + 86400;}return$day;}/*** 获取⼀周中每天的开始和结束时间* @method getDay*** @param [string] $year [年份]* @param [string] $weekday [周]** @return [array] $data [该周内每天的开始和结束时间]*/function getDay($year, $weekday){//⼀年时间$yearFirstDay = $year . '-01-01 00:00:00';$yearEndDay = $year . '-12-31 23:59:59';//第⼀天是星期⼏$week = date('N', strtotime($yearFirstDay));$days = 8 - $week;$firstWeekendDay = date('Y-m-d H:i:s', strtotime($year . '-01-0' . $days . ' 23:59:59')); $weeks = array();$weeks[1]['week_start'] = strtotime($yearFirstDay);$weeks[1]['week_end'] = strtotime($year . '-01-0' . $days . ' 23:59:59');//各周开始和结束时间戳$days2 = ((strtotime($yearEndDay) - $weeks[1]['week_end']) / 86400) / 7;$days3 = (int)floor($days2);$length = $days3 + 1;for ($i = 2; $i <= $length; $i++) {$weeks[$i]['week_start'] = 1 + $weeks[$i - 1]['week_end'];$weeks[$i]['week_end'] = 604800 + $weeks[$i - 1]['week_end'];}//最后⼀周的开始和结束时间$remainder = ((strtotime($yearEndDay) - $weeks[1]['week_end']) / 86400) % 7;if ($remainder > 0) {$data = [];$data['week_start'] = 1 + end($weeks)['week_end'];$data['week_end'] = ($remainder * 86400) + end($weeks)['week_end'];array_push($weeks, $data);}//获取每天的开始和结束时间if (array_key_exists($weekday, $weeks)) {$wEnd = $weeks[$weekday]['week_end'];$data = [];$data[1]['start'] = $weeks[$weekday]['week_start'];$data[1]['end'] = $data[1]['start'] + 86399;for ($i = 2; $i < 8; $i++) {$data[$i]['start'] = $data[$i - 1]['end'] + 1;$data[$i]['end'] = $data[$i - 1]['end'] + 86400;}return$data;};}/*** 动态获取某⽉的周的时间* @method getWeekCount*** @param [string] $year [年]* @param [string] $month [⽉]** @return [array] $weekArray [每周开始和结束周时间戳]*/function getWeekCount($year, $month){$time = $year . '-' . $month;$weekday = date('w', strtotime($time)); //获取1号是周⼏if ($weekday == 1) { //1号是周⼀$firstWeekDay = 7;} elseif ($weekday == 0) { //1号是周⽇$firstWeekDay = 1;} else {$firstWeekDay = 8 - $weekday;}$weekArray = [];$endThisweek = mktime(23, 59, 59, $month, $firstWeekDay, $year);$weekArray[1] = [strtotime($time), $endThisweek];$weeknum = 1 + ceil((date('t', $month) - $firstWeekDay) / 7); //获取到本⽉⼀共有⼏周$beginThisWeek = mktime(0, 0, 0, $month, $firstWeekDay + 1, $year);$endThisweek = mktime(23, 59, 59, $month, $firstWeekDay + 7, $year);for ($i = 2; $i <= $weeknum; $i++) {$weekArray[$i] = [($beginThisWeek + ($i - 2) * 7 * 86400), ($endThisweek + ($i - 2) * 7 * 86400)];}//获取每周的时间节点$weekArray[$weeknum] = [$weekArray[$weeknum][0], mktime(23, 59, 59, $month, date('t', strtotime($time)), $year)]; if ($year == date("Y") && $month == date("m")) {$nownum = ceil((date('d') - $firstWeekDay) / 7) + 1; //获取当前是第⼏周,如果不是当⽉默认为第⼀周} else {$nownum = 1;}return [$weekArray,$nownum];}/*** 动态获取每⽉的开始和结束时间戳* @method getMonth*** @param [string] $year [年份]** @return [array] $data [每⽉的开始和结束]*/function getMonth($year){$year = str_pad(intval($year), 4, "0", STR_PAD_RIGHT);$data = [];for ($i = 1; $i <= 12; $i++) {$month = sprintf("%02d", intval($i));$month > 12 || $month < 1 ? $month = 1 : $month = $month;$mStart = strtotime($year . $month . "01000000");$mStartCode = date("Y-m-01", $mStart);$mEnd = strtotime(date('Y-m-d 23:59:59', strtotime("$mStartCode +1 month -1 day")));$data[$i]['mstart'] = $mStart;$data[$i]['mend'] = $mEnd;}return$data;}/*** 每天的开始和结束* @method getMonthDay* deep* @param [string] $year [年]* @param [string] $month [⽉]* @return [array] $data [每天的开始和结束]*/function getMonthDay($year, $month){$month = sprintf("%02d", intval($month));$year = str_pad(intval($year), 4, "0", STR_PAD_RIGHT);$month>12 || $month<1 ? $month=1 : $month=$month;$start = strtotime($year . $month . "01000000");$startstr = date("Y-m-01", $start);$end = strtotime(date('Y-m-d 23:59:59', strtotime("$startstr +1 month -1 day")));$days = date('t',$start);$data['1']['start'] = $start;$data['1']['end'] = $data['1']['start']+86399;for ($i=2; $i <= $days ; $i++) {$data[$i]['start'] = $data[$i - 1]['end'] + 1;$data[$i]['end'] = $data[$i - 1]['end'] + 86400;}return$data;/*** 每⽉的每周的开始和结束(以七天为标准)* @method getMonthWeek* deep* @param [string] $year [年]* @param [string] $month [⽉]* @return [array] $data [每周的开始和结束]*/function getMonthWeek($year, $month){$month = sprintf("%02d", intval($month));$year = str_pad(intval($year), 4, "0", STR_PAD_RIGHT);$month>12 || $month<1 ? $month=1 : $month=$month;$start = strtotime($year . $month . "01000000");$startstr = date("Y-m-01", $start);$end = strtotime(date('Y-m-d 23:59:59', strtotime("$startstr +6 day"))); $Monthend = strtotime(date('Y-m-d 23:59:59', strtotime("$startstr +1 month -1 day"))); $days = date('t',$start);$num = ceil($days/7);$data['1']['start'] = $start;$data['1']['end'] = $end;for ($i=2; $i <= $num ; $i++) {$data[$i]['start'] = $data[$i - 1]['end'] + 1;$data[$i]['end'] = $data[$i - 1]['end'] + 604800;}$data[count($data)]['end'] = $Monthend;return$data;}/*** 得到⼀年的所有周* @method get_week* deep* @param [string] $year [年]* @return [array] $data [⼀年的所有周起始]*/function get_week($year) {//获取当年第⼀天的⽇期$yearFirstDay = $year.'-01-01 00:00:00';$yearEndDay = $year.'-12-31 23:59:59';//查看第⼀天是星期⼏$week = date('N',strtotime($yearFirstDay));//当年第⼀周的开始时间和结束时间(开始时间不⼀定是星期⼀)$days = 8-$week;$firstWeekendDay = date('Y-m-d H:i:s',strtotime($year.'-01-0'.$days.' 23:59:59')); $weeks = array();$weeks[1]['week_start'] = strtotime($yearFirstDay);$weeks[1]['week_end'] = strtotime($year.'-01-0'.$days.' 23:59:59');//组装⼀年中完整的各周开始和结束时间戳$days2 = ((strtotime($yearEndDay)-$weeks[1]['week_end'])/86400)/7;$days3 = (int)floor($days2);$length = $days3+1;for($i=2;$i<=$length;$i++) {$weeks[$i]['week_start'] = 1+$weeks[$i-1]['week_end'];$weeks[$i]['week_end'] = 604800+$weeks[$i-1]['week_end'];}//组装最后⼀周的开始和结束时间$remainder = ((strtotime($yearEndDay)-$weeks[1]['week_end'])/86400)%7;if($remainder > 0) {$data = array();$data['week_start'] = 1+end($weeks)['week_end'];$data['week_end'] = ($remainder*86400)+end($weeks)['week_end'];array_push($weeks,$data);}return$weeks;。

C#根据当前时间获取本周、本月、本季度、月初、月末待时间段值

C#根据当前时间获取本周、本月、本季度、月初、月末待时间段值

C#根据当前时间获取本周、本⽉、本季度、⽉初、⽉末待时间段值-C#根据当前时间获取本周、本⽉、本季度、⽉初、⽉末待时间段值,DateTime dt = DateTime.Now; // 当前时间DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") 24⼩时制DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") 12⼩时制DateTime startWeek = dt.AddDays( 1 - Convert.ToInt32(dt.DayOfWeek.ToString( " d " ))); //本周周⼀DateTime endWeek = startWeek.AddDays( 6 ); //本周周⽇DateTime startMonth = dt.AddDays( 1 - dt.Day); //本⽉⽉初DateTime endMonth = startMonth.AddMonths( 1 ).AddDays( - 1 ); //本⽉⽉末// DateTime endMonth = startMonth.AddDays((dt.AddMonths(1) - dt).Days - 1); //本⽉⽉末DateTime startQuarter = dt.AddMonths( 0 - (dt.Month - 1 ) % 3 ).AddDays( 1 - dt.Day); //本季度初DateTime endQuarter = startQuarter.AddMonths( 3 ).AddDays( - 1 ); //本季度末DateTime startYear = new DateTime(dt.Year, 1 , 1 ); //本年年初DateTime endYear = new DateTime(dt.Year, 12 , 31 ); //本年年末⾄于昨天、明天、上周、上⽉、上季度、上年度等等,只要AddDays()、AddMonths()、AddYears()这⼏种⽅法组合⼀下就可以了。

用php获取本周,上周,本月,上月,本季度日期的代码

用php获取本周,上周,本月,上月,本季度日期的代码

⽤php获取本周,上周,本⽉,上⽉,本季度⽇期的代码PHP date函数参数详解time()在PHP中是得到⼀个数字,这个数字表⽰从1970-01-01到现在共⾛了多少秒,很奇怪吧不过这样⽅便计算,要找出前⼀天的时间就是 time()-60*60*24;要找出前⼀年的时间就是 time()*60*60*24*365那么如何把这个数字换成⽇期格式呢,就要⽤到date函数了$t=time();echo date("Y-m-d H:i:s",$t);第⼀个参数的格式分别表⽰:a - "am" 或是 "pm"A - "AM" 或是 "PM"d - ⼏⽇,⼆位数字,若不⾜⼆位则前⾯补零; 如: "01" ⾄ "31"D - 星期⼏,三个英⽂字母; 如: "Fri"F - ⽉份,英⽂全名; 如: "January"h - 12 ⼩时制的⼩时; 如: "01" ⾄ "12"H - 24 ⼩时制的⼩时; 如: "00" ⾄ "23"g - 12 ⼩时制的⼩时,不⾜⼆位不补零; 如: "1" ⾄ 12"G - 24 ⼩时制的⼩时,不⾜⼆位不补零; 如: "0" ⾄ "23"i - 分钟; 如: "00" ⾄ "59"j - ⼏⽇,⼆位数字,若不⾜⼆位不补零; 如: "1" ⾄ "31"l - 星期⼏,英⽂全名; 如: "Friday"m - ⽉份,⼆位数字,若不⾜⼆位则在前⾯补零; 如: "01" ⾄ "12"n - ⽉份,⼆位数字,若不⾜⼆位则不补零; 如: "1" ⾄ "12"M - ⽉份,三个英⽂字母; 如: "Jan"s - 秒; 如: "00" ⾄ "59"S - 字尾加英⽂序数,⼆个英⽂字母; 如: "th","nd"t - 指定⽉份的天数; 如: "28" ⾄ "31"U - 总秒数w - 数字型的星期⼏,如: "0" (星期⽇) ⾄ "6" (星期六)Y - 年,四位数字; 如: "1999"y - 年,⼆位数字; 如: "99"z - ⼀年中的第⼏天; 如: "0" ⾄ "365"其它不在上列的字符则直接列出该字符看完上⾯的内容再看下⾯的代码有助于理解⽹上⽐较流⾏的代码段⼀<?phpecho date("Ymd",strtotime("now")), "\n";echo date("Ymd",strtotime("-1 week Monday")), "\n";echo date("Ymd",strtotime("-1 week Sunday")), "\n";echo date("Ymd",strtotime("+0 week Monday")), "\n";echo date("Ymd",strtotime("+0 week Sunday")), "\n";echo "*********第⼏个⽉:";echo date('n');echo "*********本周周⼏:";echo date("w");echo "*********本⽉天数:";echo date("t");echo "*********";echo '<br>上周起始时间:<br>';echo date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1-7,date("Y"))),"\n";echo date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y"))),"\n";echo '<br>本周起始时间:<br>';echo date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y"))),"\n";echo date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y"))),"\n";//从第⼏周找出该周的开始⽇期和结束⽇期$dayNumber = date('W') * 7;$weekDayNumber = date("w", mktime(0, 0, 0, 1, $dayNumber, date("Y")));//当前周的第⼏天$startNumber = $dayNumber - $weekDayNumber;echo date("Y-m-d", mktime(0, 0, 0, 1, $startNumber + 1, date("Y")));//开始⽇期echo date("Y-m-d", mktime(0, 0, 0, 1, $startNumber + 7, date("Y")));//结束⽇期echo '<br>上⽉起始时间:<br>';echo date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m")-1,1,date("Y"))),"\n";echo date("Y-m-d H:i:s",mktime(23,59,59,date("m") ,0,date("Y"))),"\n";echo '<br>本⽉起始时间:<br>';echo date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y"))),"\n";echo date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y"))),"\n";$season = ceil((date('n'))/3);//当⽉是第⼏季度echo '<br>本季度起始时间:<br>';echo date('Y-m-d H:i:s', mktime(0, 0, 0,$season*3-3+1,1,date('Y'))),"\n";echo date('Y-m-d H:i:s', mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y'))),"\n"; $season = ceil((date('n'))/3)-1;//上季度是第⼏季度echo '<br>上季度起始时间:<br>';echo date('Y-m-d H:i:s', mktime(0, 0, 0,$season*3-3+1,1,date('Y'))),"\n";echo date('Y-m-d H:i:s', mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y'))),"\n"; >效果图:20180331代码段⼆echo date("Ymd",strtotime("now")), "\n";echo date("Ymd",strtotime("-1 week Monday")), "\n";echo date("Ymd",strtotime("-1 week Sunday")), "\n";echo date("Ymd",strtotime("+0 week Monday")), "\n";echo date("Ymd",strtotime("+0 week Sunday")), "\n";//date('n') 第⼏个⽉//date("w") 本周周⼏//date("t") 本⽉天数echo '<br>上周:<br>';echo date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1-7,date("Y"))),"\n";echo date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y"))),"\n";echo '<br>本周:<br>';echo date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y"))),"\n";echo date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y"))),"\n";echo '<br>上⽉:<br>';echo date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m")-1,1,date("Y"))),"\n";echo date("Y-m-d H:i:s",mktime(23,59,59,date("m") ,0,date("Y"))),"\n";echo '<br>本⽉:<br>';echo date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y"))),"\n";echo date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y"))),"\n";$getMonthDays = date("t",mktime(0, 0 , 0,date('n')+(date('n')-1)%3,1,date("Y")));//本季度未最后⼀⽉天数echo '<br>本季度:<br>';echo date('Y-m-d H:i:s', mktime(0, 0, 0,date('n')-(date('n')-1)%3,1,date('Y'))),"\n";echo date('Y-m-d H:i:s', mktime(23,59,59,date('n')+(date('n')-1)%3,$getMonthDays,date('Y'))),"\n";这段代码就介绍到这了,希望⼤家以后多多⽀持。

python获取本周、上周、本月、上月及本季的时间代码实例

python获取本周、上周、本月、上月及本季的时间代码实例

python获取本周、上周、本⽉、上⽉及本季的时间代码实例前⾔本⽂主要介绍的是关于利⽤python 获取本周,上周,本⽉,上⽉,本季的时间,话不多说了,来⼀起看看实现的⽅法吧⽰例代码:import datetimefrom datetime import timedeltanow = datetime.datetime.now()# 今天today = nowprint('--- today = {}'.format(today))# 昨天yesterday = now - timedelta(days=1)print('--- yesterday = {}'.format(yesterday))# 明天tomorrow = now + timedelta(days=1)print('--- tomorrow = {}'.format(tomorrow))# 当前季度now_quarter = now.month / 3 if now.month % 3 == 0 else now.month / 3 + 1print('--- now_quarter = {}'.format(now_quarter))# 本周第⼀天和最后⼀天this_week_start = now - timedelta(days=now.weekday())this_week_end = now + timedelta(days=6 - now.weekday())print('--- this_week_start = {} this_week_end = {}'.format(this_week_start, this_week_end))# 上周第⼀天和最后⼀天last_week_start = now - timedelta(days=now.weekday() + 7)last_week_end = now - timedelta(days=now.weekday() + 1)print('--- last_week_start = {} last_week_end = {}'.format(last_week_start, last_week_end))# 本⽉第⼀天和最后⼀天this_month_start = datetime.datetime(now.year, now.month, 1)this_month_end = datetime.datetime(now.year, now.month + 1, 1) - timedelta(days=1)+ datetime.timedelta(hours=23, minutes=59, seconds=59)print('--- this_month_start = {} this_month_end = {}'.format(this_month_start, this_month_end))# 上⽉第⼀天和最后⼀天last_month_end = this_month_start - timedelta(days=1)+ datetime.timedelta(hours=23, minutes=59, seconds=59)last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)print('--- last_month_end = {} last_month_start = {}'.format(last_month_end, last_month_start))# 本季第⼀天和最后⼀天month = (now.month - 1) - (now.month - 1) % 3 + 1this_quarter_start = datetime.datetime(now.year, month, 1)this_quarter_end = datetime.datetime(now.year, month + 3, 1) - timedelta(days=1)+ datetime.timedelta(hours=23, minutes=59, seconds=59)print('--- this_quarter_start = {} this_quarter_end = {}'.format(this_quarter_start, this_quarter_end))# 上季第⼀天和最后⼀天last_quarter_end = this_quarter_start - timedelta(days=1)+ datetime.timedelta(hours=23, minutes=59, seconds=59)last_quarter_start = datetime.datetime(last_quarter_end.year, last_quarter_end.month - 2, 1)print('--- last_quarter_start = {} last_quarter_end = {}'.format(last_quarter_start, last_quarter_end))# 本年第⼀天和最后⼀天this_year_start = datetime.datetime(now.year, 1, 1)this_year_end = datetime.datetime(now.year + 1, 1, 1) - timedelta(days=1)+ datetime.timedelta(hours=23, minutes=59, seconds=59)print('--- this_year_start = {} this_year_end = {}'.format(this_year_start, this_year_end))# 去年第⼀天和最后⼀天last_year_end = this_year_start - timedelta(days=1)+ datetime.timedelta(hours=23, minutes=59, seconds=59)last_year_start = datetime.datetime(last_year_end.year, 1, 1)print('--- last_year_start = {} last_year_end = {}'.format(last_year_start, last_year_end))总结到此这篇关于利⽤python获取本周、上周、本⽉、上⽉及本季的时间的⽂章就介绍到这了,更多相关python获取本周、上周、本⽉、上⽉及本季时间内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。

MySQL查询当天、本周,本月、上一个月的数据

MySQL查询当天、本周,本月、上一个月的数据

MySQL查询当天、本周,本⽉、上⼀个⽉的数据mysql查询当天的所有信息:SELECT *FROM 表名WHERE year(时间字段名)=year(now()) and month(时间字段名) = month(now()) and day(时间字段名) = day(now());这个有⼀些繁琐,还有简单的写法:SELECT *FROM表名WHERE date(时间字段名) = curdate();另⼀种写法没测试过查询当天的记录SELECT *FROM 表名WHERE TO_DAYS(时间字段名) = TO_DAYS(NOW());date()函数获取⽇期部分, 扔掉时间部分,然后与当前⽇期⽐较即可补充:本周、上周、本⽉、上个⽉份的数据查询当前这周的数据SELECT * FROM表名WHERE YEARWEEK(date_format(时间字段名,'%Y-%m-%d')) = YEARWEEK(now());查询上周的数据SELECT * FROM表名WHERE YEARWEEK(date_format(时间字段名,'%Y-%m-%d')) = YEARWEEK(now())-1;查询当前⽉份的数据SELECT * FROM 表名WHERE date_format(时间字段名,'%Y-%m') = date_format(now(),'%Y-%m')查询距离当前现在6个⽉的数据SELECT * FROM表名WHERE 时间字段名between date_sub(now(),interval 6month) and now();查询上个⽉的数据SELECT * FROM表名WHERE date_format(时间字段名,'%Y-%m') = date_format(DATE_SUB(curdate(), INTERVAL 1MONTH), '%Y-%m');SELECT *FROM表名WHERE DATE_FORMAT(时间字段名,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m') ;SELECT *FROM表名WHERE WEEKOFYEAR(FROM_UNIXTIME(时间字段名,'%y-%m-%d')) = WEEKOFYEAR(now());SELECT *FROM表名WHERE MONTH(FROM_UNIXTIME(时间字段名,'%y-%m-%d')) =MONTH(now());SELECT *FROM表名WHERE YEAR(FROM_UNIXTIME(时间字段名,'%y-%m-%d')) =YEAR(now()) and MONTH(FROM_UNIXTIME(时间字段名,'%y-%m-%d')) =MONTH(now()); SELECT *FROM表名WHERE 时间字段名between上⽉最后⼀天and下⽉第⼀天;mysql查询多少秒内的数据SELECT count( * ) AS c, sum( if( logusertype = 2, logusertype, 0 ) ) / 2AS a, sum( if( logusertype = 3, logusertype, 0 ) ) /3AS bFROM testlog WHERE UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP( logendtime )<=30查询30秒内记录的总数,loguser等于2的记录的总数和,和 loguser等于3的记录的总数.if( logusertype = 2, logusertype, 0 ) 如果logusetype等于2 就在logusertype上累加,否则加0。

mysql中获取一天、一周、一月时间数据的各种sql语句写法

mysql中获取一天、一周、一月时间数据的各种sql语句写法

mysql中获取⼀天、⼀周、⼀⽉时间数据的各种sql语句写法创建表:复制代码代码如下:create table if not exists t(id int,addTime datetime default '0000-00-00 00:00:00′)添加两条初始数据:insert t values(1, '2012-07-12 21:00:00′);insert t values(2, '2012-07-22 21:00:00′);1、传统对⽐判断:SELECT * FROM `t` WHERE DATE_FORMAT(addTime,'%Y-%m-%d') = date_format(now(),'%Y-%m-%d')");2、第⼀点的简写:SELECT * FROM `t` WHERE addTime >= date_format(NOW(),'%Y-%m-%d');3、利⽤函数判断:SELECT * FROM `t` WHERE DATEDIFF(addTime,NOW()) =0;//推荐此⽅法4、利⽤时间戳判断:SELECT * FROM `t` WHERE addTime BETWEEN (UNIX_TIMESTAMP(now()-86440)) AND now();注:返回当天时间的mysql函数有CURDATE()、CURRENT_DATE()、CURRENT_DATE、NOW()⼏种;其中NOW()获取的⽇期格式为0000-00-00 00:00:00的时间;CURDATE()、CURRENT_DATE()、CURRENT_DATE是获取⽇期格式为0000-00-00的时间,所以返回的时间⽆时分秒;1、今天是当⽉的第⼏天:SELECT DAYOFMONTH( NOW( ) );2、获取当⽉的第⼀天时间:SELECT DATA_SUB( NOW(), INTERVAL DAYOFMONTH(NOW()) – 1 DAY);⽇期运算函数,句型:date_add(date,INTERVAL expr type)和date_sub(date,INTERVAL expr type)date为⼀个datetime或date值,可当作起始时间,expr为⼀个表达式,⽤来指定增加或减少的时间间隔数⽬,可为⼀个字符串–若为负值,则在表达式前加个"-"符号。

sql语句获取今天、昨天、近7天、本周、上周、本月、上月、半年数据

sql语句获取今天、昨天、近7天、本周、上周、本月、上月、半年数据

sql语句获取今天、昨天、近7天、本周、上周、本⽉、上⽉、半年数据sql语句获取今天、昨天、近7天、本周、上周、本⽉、上⽉、半年数据01 话说有⼀⽂章表article,存储⽂章的添加⽂章的时间是add_time字段,该字段为int(5)类型的,现需要查询今天添加的⽂章总数并且按照时间从⼤到⼩排序,则查询语句如下:0203 1 select * from `article` where date_format(from_UNIXTIME(`add_time`),'%Y-%m-%d') = date_format(now(),'%Y-%m-%d');04 或者:0506 1 select * from `article` where to_days(date_format(from_UNIXTIME(`add_time`),'%Y-%m-%d')) = to_days(now());07 假设以上表的add_time字段的存储类型是DATETIME类型或者TIMESTAMP类型,则查询语句也可按如下写法:0809 查询今天的信息记录:1011 1 select * from `article` where to_days(`add_time`) = to_days(now());12 查询昨天的信息记录:1314 1 select * from `article` where to_days(now()) – to_days(`add_time`) <= 1;15 查询近7天的信息记录:1617 1 select * from `article` where date_sub(curdate(), INTERVAL 7 DAY) <= date(`add_time`);18 查询近30天的信息记录:1920 1 select * from `article` where date_sub(curdate(), INTERVAL 30 DAY) <= date(`add_time`);21 查询本⽉的信息记录:2223 1 select * from `article` where date_format(`add_time`, ‘%Y%m') = date_format(curdate() , ‘%Y%m');24 查询上⼀⽉的信息记录:2526 1 select * from `article` where period_diff(date_format(now() , ‘%Y%m') , date_format(`add_time`, ‘%Y%m')) =1;27 对上⾯的SQL语句中的⼏个函数做⼀下分析:2829 (1)to_days3031 就像它的名字⼀样,它是将具体的某⼀个⽇期或时间字符串转换到某⼀天所对应的unix时间戳,如:3233 01 mysql> select to_days('2010-11-22 14:39:51');34 02 +--------------------------------+35 03 | to_days('2010-11-22 14:39:51') |36 04 +--------------------------------+37 05 | 734463 |38 06 +--------------------------------+39 0740 08 mysql> select to_days('2010-11-23 14:39:51');41 09 +--------------------------------+42 10 | to_days('2010-11-23 14:39:51') |43 11 +--------------------------------+44 12 | 734464 |45 13 +--------------------------------+46 可以看出22⽇与23⽇的差别就是,转换之后的数增加了1,这个粒度的查询是⽐较粗糙的,有时可能不能满⾜我们的查询要求,那么就需要使⽤细粒度的查询⽅法str_to_date函数了,下⾯将分析这个函数的⽤法。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

获取本日,本周,本月的开始时间戳和结束时间戳
这是我最近尝试写的一个程序,可能有许多不足之处,还请见谅。

这是一个类,类里面主要有两个方法。

一个是timeToTimestamp (),一个是getTime()。

前者负责将时间转化成时间戳,后者则负责判断filter值,然后设置相应的date时间。

注:filter=1 代表本日,filter=2 代表本周,filter=3代表本月。

class TimestampUtils{
private static long startTime = -1;
private static long endTime = -1;
public static void getTime (int filter){
Calendar cal =Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd" ); //设置星期一为一周的开始日
cal.setFirstDayOfWeek(Calendar.MONDAY);
switch(filter){
case 1://今天
startTime = timeToTimestamp(format.format(new Date())+" 00:00: 00");
endTime = timeToTimestamp(format.format(new Date())+" 23:59: 59");
break;
case 2://本周
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
startTime = timeToTimestamp(format.format(cal.getTime())+" 00:0 0:00");
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
endTime = timeToTimestamp(format.format(cal.getTime())+" 23:5 9:59");
break;
case 3://本月
cal.set(Calendar.DATE, cal.getActualMinimum(Calendar.DATE)); startTime = timeToTimestamp(format.format(cal.getTime())+" 00:0 0:00");
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE)) ;
endTime = timeToTimestamp(format.format(cal.getTime())+" 23:5 9:59");
break;
default:
break;
}
}
//将时间转换成时间戳
public static long timeToTimestamp (String dateTime){
SimpleDateFormat format2 = new SimpleDateFormat( "yyyy-MM-d d HH:mm:ss" );
long time = -1;
try {
time = format2.parse(dateTime).getTime();
} catch (ParseException e) {
printStackTrace();
}
return time;
}
}。

相关文档
最新文档