自定义获取时间戳以及获取指定时间周,月,季,年的开始时间和结束时间戳

本文介绍了一种处理时间戳的方法,包括将时间戳转换为指定格式,以及生成基于特定日期的时间区间。涵盖了从单一时间点到当前时间,以及固定日期范围的处理,还提供了获取当前周、月、季、年的时间区间的函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*传入时间戳格式,组装时间戳为数组. 注意:Y-m-d格式
    *如果参数1是今天时间戳且第二个参数为空,返回0点至当前时间的时间戳.
    如果不是且第二个为空,返回0点至0点的时间戳
    如果第二个参数存在,组装时间戳为数组进行返回*/
    public function timeStamp($time, $time1 = null){
    	$time = is_numeric($time)?$time:strtotime($time);
    	if($time1)
    		$time1 = is_numeric($time1)?$time1:strtotime($time1);
    	if($time == strtotime(date('Y-m-d')) && empty($time1)){
    		$timeo = $time;
    		$timet = time();
    	}elseif(empty($time1)){
    		$timeo = $time;
    		$timet = $time+86400;
    	}else{
    		$timeo = $time;
    		$timet = $time1;
    	}
    	return compact(['time', 'timet']);
    }
//查询当前所在周的开始时间和结束时间的时间戳
	public function getWeekTime($date = NULL){
	    $timestamp=empty($date)?strtotime('now'):(is_numeric($date)?$date:strtotime($date));
	    $w=strftime('%w',$timestamp);
	    $date=array();
	    $time=$timestamp-($w-1)*86400;
	    $timet=$timestamp+(7-$w)*86400;
    	return compact('time', 'timet');
	}
//查询当前所在月的开始时间和结束时间的时间戳
	public function getMonthTime($date = NULL){
	    $timestamp=empty($date)?strtotime('now'):(is_numeric($date)?$date:strtotime($date));
	    $m=strftime('%e',$timestamp);
	    $days = date("t", $timestamp);
	    $time = $timestamp-($m-1)*86400;
	    $timet = $timestamp+($days+1-$m)*86400;
	    return compact('time', 'timet');
	}
//查询当前所在季的开始时间和结束时间的时间戳
	public function getSeasonTime($date){
		$date = is_numeric($date)?date('Y-m-d H:i:s', $date):$date;

		$season = ceil((int)str_cut($date,'-',1)/3);
		$time = mktime(0,0,0,($season - 1) *3 +1,1,str_cut($date));
		$timet = mktime(0,0,0,$season * 3,1,str_cut($date));

		return compact('time', 'timet');
	}
//查询当前所在年的开始时间和结束时间的时间戳
	public function getYearTime($date){
		$date = is_numeric($date)?date('Y-m-d H:i:s', $date):$date;
		$time = mktime(0,0,0,1,1,str_cut($date));
		$timet = mktime(0,0,0,1,1,str_cut($date)+1);

		return compact('time', 'timet');
	}

 

<think>我们使用Java8的java.timeAPI来计算最近12个开始时间结束时间。思路:1.获取当前日期(如果用户指定了日期,则使用指定日期)2.计算从当前开始的最近12个(包括当前)3.对于每个,计算该的第一天(开始时间最后一天(结束时间)4.注意:开始时间时间部分为00:00:00,结束时间为23:59:59.999999999(或根据需要调整精度)由于用户需求是最近12个(可能包括当前或从当前往前推12个),这里我们理解为从当前往前推12个(即包括当前共12个)。有两种常见理解:a)最近12个:从当前往前推11个,加上当前(共12个)b)从当前开始,包括当前,往前的12个(也是共12个)这里我们按照第一种:比如今天是2024-08-15,那么最近12个指的是2023-09至2024-08(共12个)步骤:1.获取当前日期(或指定日期)所在的份(YearMonth)2.从当前份的前11个开始(即减去11个)直到当前份,一共12个3.对于每一个份,使用YearMonth的atDay(1)得到第一天的LocalDate(作为开始日期)4.使用YearMonth的atEndOfMonth()得到最后一天的LocalDate(作为结束日期)5.如果需要时间部分,可以将LocalDate转换为当天的开始时间(LocalDateTime)结束时间(LocalDateTime)注意:用户问题中提到了“精确到毫秒”,但通常份区间我们只关心日期部分,但如果需要时间部分,我们可以:开始时间:当天的00:00:00.0结束时间:当天的23:59:59.999999999或23:59:59.999(毫秒级)但请注意,在Java中,LocalTime的精度可以到纳秒,而LocalDateTime可以表示到纳秒。另外,有时业务上需要将结束时间设为下个的第一天00:00:00(左闭右开区间),但这里用户要求是开始结束时间,所以我们按照自然提供。根据引用[1]引用[2],我们可以这样实现:实现方案:1.获取当前日期(或指定日期)的YearMonth。2.创建一个列表,用于存放12个开始结束时间。3.循环12次,从当前的前11个开始(即i=11;i>=0;i--)直到当前。示例代码:我们将输出每个开始结束时间(日期部分),如果需要时间部分,可以加上时间并转换为需要的格式。下面我们给出两种方式:一种是只返回日期(LocalDate),另一种是返回精确到毫秒的日期时间(LocalDateTime)。由于问题要求的是“开始时间结束时间”,这里我们默认返回日期时间格式,其中:开始时间:当天的00:00:00.000结束时间:当天的23:59:59.999但注意:LocalDateTime没有时区,如果需要带时区的结束时间,可以转换为ZonedDateTime然后调整,但这里不涉及时区。另外,我们也可以使用另一种方式:使用时间戳(毫秒数),但用户没有明确要求,我们提供LocalDateTime格式。代码实现:方法:获取最近12个每个开始结束时间(精确到毫秒)步骤:1.获取当前日期(指定日期)的YearMonth2.计算前11个的起始份(即从当前往前推11个)3.循环12个(包括当前)4.对每个,生成两个LocalDateTime:开始时间:YearMonth.atDay(1).atTime(0,0,0,0).withNano(0)然后我们可以调整到毫秒级,但通常00:00:00的毫秒也是0结束时间:YearMonth.atEndOfMonth().atTime(23,59,59,999000000)//将纳秒调整为999毫秒(即999000000纳秒)但是,如果我们希望精确到毫秒,可以这样:开始时间:LocalDateTime.of(YearMonth.atDay(1),LocalTime.MIN).withNano(0)//其实MIN就是00:00:00.0结束时间:LocalDateTime.of(YearMonth.atEndOfMonth(),LocalTime.MAX).withNano(0)//MAX是23:59:59.999999999,但是用户要求毫秒,我们可以截断到毫秒?或者直接设置为23:59:59.999不过,由于LocalTime.MAX表示的是23:59:59.999999999,如果我们想要毫秒级的结束时间23:59:59.999,我们可以:结束时间=LocalDateTime.of(YearMonth.atEndOfMonth(),LocalTime.of(23,59,59,999000000))但注意:如果业务上需要,也可以使用另一种方法:开始时间用当天的00:00:00,结束时间用第二天的00:00:00减1毫秒。但这里我们不这样处理。我们按照自然的当天最大时间作为结束时间。为了简化,我们可以提供两个方法:一个是只返回日期(LocalDate),另一个返回精确到毫秒的LocalDateTime。根据用户的问题,他可能需要精确到毫秒,所以我们提供LocalDateTime。另外,用户可能需要两个日期时间之间的毫秒数?但问题没有要求,所以我们只返回开始结束的LocalDateTime。下面我们编写代码:注意:如果用户指定了日期,则以该日期为基准;否则使用当前日期。示例代码:我们将创建一个方法,该方法接收一个LocalDate参数(基准日期),返回一个列表,列表元素为每个开始结束时间(使用数组或自定义类)。自定义类:MonthRange(包含LocalDateTime类型的startend)但是,引用[1]中,用户只是打印了的字符串,但我们的需求是每个开始结束时间(精确到毫秒),所以需要调整。另外,用户可能要求返回最近12个的区间(即从当前往前推12个,但不包括当前?)这里我们按照包括当前,往前推12个(即12个,从当前的前11个开始当前)?再次明确:最近12个,通常指的是当前以及之前的11个(共12个)。例如当前2024-08,则从2023-09开始到2024-08。因此,我们将循环12次,计算每个开始结束时间。具体代码:我们定义一个类来存储开始结束时间(如果需要可以在外部定义):</think> 我将为您提供一个完整的 Java 解决方案,使用 Java 8 的 `java.time` API 计算最近 12 个(包括当前)的开始结束时间,精确到毫秒: ```java import java.time.*; import java.time.format.DateTimeFormatter; import java.util.*; public class RecentMonthsCalculator { public static void main(String[] args) { // 可指定基准日期,或默认使用当前日期 LocalDate referenceDate = LocalDate.of(2024, 8, 15); // 基准日期 List<MonthRange> months = calculateRecent12Months(referenceDate); // 输出结果 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"); System.out.printf("基于基准时间 [%s] 的最近12个区间:\n", referenceDate); months.forEach(range -> { System.out.printf("%s: %s 至 %s\n", range.getYearMonth(), range.getStartTime().format(formatter), range.getEndTime().format(formatter) ); }); } /** * 计算基准日期前12个份区间(包括当前) * * @param referenceDate 基准日期 * @return 包含12个MonthRange对象的列表 */ public static List<MonthRange> calculateRecent12Months(LocalDate referenceDate) { List<MonthRange> ranges = new ArrayList<>(12); YearMonth currentMonth = YearMonth.from(referenceDate); for (int i = 11; i >= 0; i--) { YearMonth month = currentMonth.minusMonths(i); ranges.add(createMonthRange(month)); } return ranges; } /** * 创建单个份的时间区间 * * @param month 目标份 * @return 包含起始时间结束时间的MonthRange对象 */ private static MonthRange createMonthRange(YearMonth month) { // 开始时间初第一天的00:00:00.000) LocalDateTime start = month.atDay(1).atStartOfDay(); // 结束时间末最后一天的23:59:59.999) LocalDateTime end = month.atEndOfMonth().atTime(LocalTime.MAX).withNano(999000000); return new MonthRange(month, start, end); } static class MonthRange { private final YearMonth yearMonth; private final LocalDateTime startTime; private final LocalDateTime endTime; public MonthRange(YearMonth yearMonth, LocalDateTime startTime, LocalDateTime endTime) { this.yearMonth = yearMonth; this.startTime = startTime; this.endTime = endTime; } public String getYearMonth() { return yearMonth.toString(); // 格式: "yyyy-MM" } public LocalDateTime getStartTime() { return startTime; } public LocalDateTime getEndTime() { return endTime; } } } ``` ### 关键功能说明 1. **时间区间计算**: - 获取基准日期的当前份作为终点 $$M_c$$ - 计算 $$M_c$$ 前 11 个作为起点 $$M_s$$ - 生成区间:$$[M_s, M_s + 1, ..., M_c]$$ 2. **时间精度处理**: - **开始时间**:每第一天的 $$00:00:00.000$$ - **结束时间**:每最后一天的 $$23:59:59.999$$ 3. **闰处理**: - 使用 `YearMonth.atEndOfMonth()` 自动处理不同份的天数差异 - 闰自动计算为 29 天 ### 数学表示 对于给定基准日期 $$d$$,计算: $$\text{份集合} = \{ \text{YearMonth}(d) - k \mid k \in [0, 11] \}$$ 各边界条件: $$\begin{cases} \text{起始点} = M_1\text{日} \oplus \text{00:00:00.000} \\ \text{结束点} = M_n\text{日} \oplus \text{23:59:59.999} \end{cases}$$ ### 示例输出 当基准日期为 2024-08-15 时: ``` 基于基准时间 [2024-08-15] 的最近12个区间: 2023-09: 2023-09-01 00:00:00.000 至 2023-09-30 23:59:59.999 2023-10: 2023-10-01 00:00:00.000 至 2023-10-31 23:59:59.999 ... 2024-07: 2024-07-01 00:00:00.000 至 2024-07-31 23:59:59.999 2024-08: 2024-08-01 00:00:00.000 至 2024-08-31 23:59:59.999 ``` ### 特殊优势 1. **毫秒级精度**:精确处理时间边界,适合日志查询等场景 2. **时区安全**:使用 `LocalDateTime` 避免时区转换问题 3. **性能优化**:$$O(1)$$ 时间复杂度完成每计算 该方案完整解决了最近12个时间区间的精确计算需求[^1][^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值