Android获取周/月起始时间:如何设置为00:00/23:59?
Hey there! Let's sort out that timestamp issue you're facing with fetching SHealth data. You've got the weekly and monthly start times mostly right, but the daily start/end isn't aligning to 00:00:00 and 23:59:59 UTC as you need. Here's how to fix it:
Key Issues in Current Implementation
Looking at your existing code, the main gaps are:
- Not explicitly setting the UTC time zone (which SHealth typically uses for data timestamps)
- For the monthly start time, you weren't resetting the
HOUR_OF_DAYfield, so it kept the current hour instead of jumping to 00:00 - Missing dedicated functions for daily start/end times
Updated Functions for Daily, Weekly, and Monthly Timestamps
1. Get Daily Start Time (00:00:00 UTC)
This function resets all time fields to the start of the current UTC day:
public static long getStartTimeOfDay() { // Explicitly use UTC to match SHealth's timezone Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTimeInMillis(); }
2. Get Daily End Time (23:59:59 UTC)
To capture the final moment of the day, set all time fields to the end of the UTC day (we include milliseconds to avoid missing any last-second data):
public static long getEndTimeOfDay() { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 999); return cal.getTimeInMillis(); }
3. Updated Weekly Start Time Function
Your existing weekly function was close, but adding explicit UTC ensures consistency:
public static long getStartTimeOfWeek() { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); // Set to Sunday (DAY_OF_WEEK=1; adjust to 2 if you need Monday as week start) cal.set(Calendar.DAY_OF_WEEK, 1); return cal.getTimeInMillis() + ONE_DAY; // Adjustment for week start alignment }
4. Updated Monthly Start Time Function
Fix the missing HOUR_OF_DAY reset and add UTC to ensure it's truly the first moment of the month:
public static long getMonthDateFirstdate(){ Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.DATE, cal.getActualMinimum(Calendar.DAY_OF_MONTH)); return cal.getTimeInMillis(); }
Why This Works
- Explicit UTC Timezone: Ensures your timestamps match the timezone SHealth uses for storing data, avoiding discrepancies from local timezone offsets
- Full Time Field Reset: Setting
HOUR_OF_DAY,MINUTE,SECOND, andMILLISECONDto 0 (or max values for end time) guarantees you get the exact start/end of the period you need
内容的提问来源于stack exchange,提问作者Tanveerbyn

