遇到复杂的日期处理场景?看这篇总结就够了(JAVA)

咱们继续学Java——高级篇 第九十五篇:之Java 8日期时间API(日期调整器与部分日期类) 大家好!在我们之前对Java 8日期时间API中时间线(`Instant`)和本地时间(`LocalDate`)的学习基础上,今天我们将继续深入探讨该API中的日期调整器(`TemporalAdjusters`)以及部分日期类(如 `MonthDay`、`YearMonth` 和 `Year`)的相关知识。我希望通过这篇博客,用通俗易懂的语言为大家详细讲解这些特性的作用和使用方法,让大家能够更加灵活地处理日期相关的计算和操作。在实际的日程安排、数据分析等应用场景中,这些功能可以帮助我们更方便地计算特定日期、 阅读详情

前言

  日常开发中我们经常涉及到对日期的处理,这篇博客整理了常用的日期处理方法。

代码实现:

import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Slf4j
public class DateUtils {

    /**
     * 将某格式的时间字符串转化成毫秒时间戳表示的字符串
     *
     * @param dateTime 时间字符串
     * @param format   时间字符串的格式
     * @return 毫秒时间戳表示的字符串,例如"1609459200000ms"
     */
    // 将某格式的时间字符串转化成毫秒时间戳表示的字符串
    public static String dateTimeStrToMills(String dateTime, String format) {
        String dateStr = null;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        try {
            Date d = new Date();
            d = sdf.parse(dateTime);
            calendar.setTime(d);
            dateStr = calendar.getTimeInMillis() + "ms";
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateStr;
    }

    /**
     * 将某格式的时间字符串转化成毫秒时间戳的长整型值
     *
     * @param dateTime 时间字符串
     * @param format   时间字符串的格式
     * @return 毫秒时间戳的长整型值
     * @throws ParseException 如果输入的日期时间字符串格式不正确,则抛出此异常
     */
    public static long dateTimeStrToMillsValue(String dateTime, String format) {
        long dateValue = 0L;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        try {
            Date d = new Date();
            d = sdf.parse(dateTime);
            calendar.setTime(d);
            dateValue = calendar.getTimeInMillis();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateValue;
    }

    /**
     * 获取某个月的天数
     *
     * @param year  年份
     * @param month 月份(从0开始计数,即1月对应0)
     * @return 对应月份的天数
     */
    public static int getDayNumOfMonth(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(year, month, 0);
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取某日、月、年前后的日期
     *
     * @param num      表示要增加或减少的时间单位数量,正数表示未来的日期,负数表示过去的日期
     * @param date      给定的日期字符串,格式需与format参数一致
     * @param format    日期字符串的格式
     * @param timeType  时间类型,可以是Calendar.YEAR(年)、Calendar.MONTH(月)、Calendar.DAY_OF_MONTH(日)等
     * @return 计算后的日期字符串,格式与输入的date参数一致
     * @throws ParseException 如果输入的日期字符串格式不正确,则抛出此异常
     */
    public static String getBeforeOrAfterDateType(int num, String date, String format, int timeType) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String resultDate = "";
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        try {
            Date d = new Date();
            d = sdf.parse(date);
            calendar.setTime(d);
            calendar.add(timeType, num);//一天的结束是第二天的开始
            resultDate = sdf.format(calendar.getTime());
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return resultDate;
    }

    /**
     * 根据毫秒时间戳获得格式化后的日期
     *
     * @param millisecond 毫秒时间戳
     * @param dateFormat  日期格式,例如 "yyyy-MM-dd HH:mm:ss"
     * @return 格式化后的日期字符串
     */
    public static String millisecondToDate(Long millisecond, String dateFormat) {
        Date date = new Date(millisecond);
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(date);
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        String sb = format.format(gc.getTime());
        return sb;
    }

    /**
     * 将毫秒时间戳转换为指定格式的日期字符串,并应用指定的时区。
     *
     * @param millisecond 毫秒时间戳
     * @param dateFormat  日期格式,如 "yyyy-MM-dd HH:mm:ss"
     * @param timeZoneId  时区ID,如 "GMT+8"
     * @return 转换后的日期字符串
     */
    public static String convertTimestampToFormattedDate(long millisecond, String dateFormat, String timeZoneId) {
        Date date = new Date(millisecond);
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(date);

        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
        format.setTimeZone(timeZone);

        String sb = format.format(gc.getTime());
        return sb;
    }

    /**
     * 获取某月的第一天。
     *
     * @param year  年份
     * @param month 月份(注意:月份从1开始计数,但Calendar类内部月份是从0开始计数的,因此需减1)
     * @return 返回指定月份第一天的日期字符串,格式为"yyyy-MM-dd"
     */
    public static String getFirstDayOfMonth(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        int firstDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        cal.set(Calendar.DAY_OF_MONTH, firstDay);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String firstDayOfMonth = sdf.format(cal.getTime());
        return firstDayOfMonth;
    }

    /**
     * 获取某月的最后一天。
     *
     * @param year  年份
     * @param month 月份(注意:月份从1开始计数,但Calendar类内部月份是从0开始计数的,因此需减1)
     * @param format 日期格式,例如 "yyyy-MM-dd"
     * @return 返回指定月份最后一天的日期字符串,格式与输入的format参数一致
     */
    public static String getLastDayOfMonth(int year, int month, String format) {
        Calendar cal = Calendar.getInstance();
        cal.clear();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month - 1);
        int lastDay = 0;
        lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String lastDayOfMonth = sdf.format(cal.getTime());
        return lastDayOfMonth;
    }

    /**
     * 获取起止日期之间的所有日期字符串(可自定义间隔、格式、日期类型)
     *
     * @param begin     开始日期字符串
     * @param end       结束日期字符串
     * @param num       日期间隔数量
     * @param timeType  日期类型,可以是Calendar.YEAR(年)、Calendar.MONTH(月)、Calendar.DAY_OF_MONTH(日)等
     * @param format    日期字符串的格式
     * @return 返回起止日期之间的所有日期字符串列表
     * @throws ParseException 如果输入的日期字符串格式不正确,则抛出此异常
     */
    public static List<String> getDatesBetweenTwoDate(String begin, String end, int num, int timeType, String format) {
        List<String> lDates = new ArrayList<>();
        if (begin.equals(end)) {
            lDates.add(begin);
            return lDates;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date beginDate = sdf.parse(begin);
            Date endDate = sdf.parse(end);
            lDates.add(sdf.format(beginDate));
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(beginDate);
            boolean bContinue = true;
            while (bContinue) {
                calendar.add(timeType, num);
                if (endDate.after(calendar.getTime())) {
                    lDates.add(sdf.format(calendar.getTime()));
                } else {
                    break;
                }
            }
            lDates.add(sdf.format(endDate));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return lDates;
    }

    /**
     * 获取当前日期和时间。
     *
     * @return 当前日期和时间的Date对象
     * @throws ParseException 如果解析日期字符串时发生错误,则抛出此异常
     */
    public static Date getCurrentDateTime() throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        return formatter.parse(formatter.format(date));
    }

    /**
     * 获取当前日期和时间的字符串表示。
     *
     * @return 当前日期和时间的字符串表示,格式为"yyyy-MM-dd HH:mm:ss"
     */
    public static String getCurrentDateTimeStr() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        return formatter.format(date);
    }

    /**
     * 将给定的Date对象转换为字符串形式。
     *
     * @param dateTime 要转换的Date对象
     * @return 转换后的日期字符串,格式为"yyyy-MM-dd HH:mm:ss"
     */
    public static String dateToString(Date dateTime) {
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = sdf2.format(dateTime);
        return strDate;
    }

    /**
     * 将给定时间转为太平洋时间(美国洛杉矶时间)。
     *
     * @param date 给定的时间,类型为Date
     * @return 转换后的太平洋时间字符串,格式为"yyyy-MM-dd HH:mm:ss"
     */
    public static String changeTimeToPacificTime(Date date) {
        //将给定时间转为太平洋时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
        String pacificTime = sdf.format(date);
        return pacificTime;
    }

    /**
     * 将太平洋时间(美国洛杉矶时间)转换为北京时间。
     *
     * @param time 太平洋时间字符串,格式为"yyyy-MM-dd HH:mm:ss"
     * @return 转换后的北京时间字符串,格式为"yyyy-MM-dd HH:mm:ss"
     * @throws RuntimeException 如果输入的太平洋时间字符串格式不正确,则抛出此异常
     */
    public static String changePacificTimeToCST(String time) {
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf2.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
        Date date = null;
        try {
            date = sdf2.parse(time);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        //将太平洋时间转成北京时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String cstTime = sdf.format(date);
        return cstTime;
    }

    /**
     * 将太平洋时间(美国洛杉矶时间)转换为UTC时间。
     *
     * @param time 太平洋时间字符串,格式为"yyyy-MM-dd HH:mm:ss"
     * @return 转换后的UTC时间字符串,格式为"dd/MM/yyyy"
     * @throws RuntimeException 如果输入的太平洋时间字符串格式不正确,则抛出此异常
     */
    public static String changePacificTimeToUTC(String time) {
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf2.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
        Date date = null;
        try {
            date = sdf2.parse(time);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        //将太平洋时间转成北京时间
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        return sdf.format(date);
    }

    /**
     * 将给定的太平洋时间字符串转换为时间戳。
     *
     * @param time 太平洋时间字符串,格式为"yyyy-MM-dd HH:mm:ss"
     * @return 转换后的时间戳
     * @throws RuntimeException 如果输入的太平洋时间字符串格式不正确,则抛出此异常
     */
    public static long getPacificTimeTimestamp(String time) {
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf2.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
        Date date = null;
        long timestamp;
        try {
            date = sdf2.parse(time);
            timestamp = date.getTime();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return timestamp;
    }

    /**
     * 将给定的时间字符串转换为时间戳。
     *
     * @param time 时间字符串,格式为"yyyy-MM-dd HH:mm:ss"
     * @return 转换后的时间戳
     * @throws RuntimeException 如果输入的时间字符串格式不正确,则抛出此异常
     */
    public static long getCSTTimestamp(String time) {
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        long timestamp;
        try {
            date = sdf2.parse(time);
            timestamp = date.getTime();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return timestamp;
    }

    /**
     * 将字符串转换为日期对象。
     *
     * @param dateStr 要转换的日期字符串
     * @param format  日期字符串的格式
     * @return 转换后的日期对象,如果转换失败则返回null
     */
    public static Date StringToDate(String dateStr, String format) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = dateFormat.parse(dateStr);
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        return date;
    }

    /**
     * 获取月环比的时间段。
     *
     * @param startTime 开始时间字符串
     * @param endTime   结束时间字符串
     * @param format    日期格式
     * @return 包含环比开始时间和结束时间的Map,键分别为"comparedStartTime"和"comparedEndTime"
     */
    public static Map<String, String> getMoMTimePeriod(String startTime, String endTime, String format) {
        // 计算出两个用户日期之间相隔多少天,然后开始时间往前按间隔得到环比的开始时间,环比结束时间为开始时间的前一天
        Map<String, String> result = new HashMap<>();
        List<String> dates = getDatesBetweenTwoDate(startTime, endTime, 1, Calendar.DAY_OF_MONTH, format);
        int intervalDay = dates.size();
        result.put("comparedStartTime", getBeforeOrAfterDateType(-intervalDay, startTime, format, Calendar.DAY_OF_MONTH));
        result.put("comparedEndTime", getBeforeOrAfterDateType(-1, startTime, format, Calendar.DAY_OF_MONTH));
        return result;
    }

    /**
     * 获取当前时间的UTC/GMT时间字符串。
     *
     * @return 返回当前时间的UTC/GMT时间字符串,格式为"EEE, d MMM yyyy HH:mm:ss 'GMT'"
     */
    public static String getUTCGMTTimeStr() {
        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // 设置时区为GMT
        String str = sdf.format(cd.getTime());
        return str;
    }

    /**
     * 将给定的Date对象转换为日期字符串。
     *
     * @param date 要转换的Date对象
     * @return 转换后的日期字符串,格式为"dd/MM/yyyy"
     */
    public static String getDateStr(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
        String str = sdf.format(date);
        return str;
    }

    // 获取当天零点时间戳-----Proxy为Remo获取太平洋时间当天零点时间戳,Proxy为Korea获取首尔时间当天零点时间戳
    public static Long getZeroTimestampMillis(String proxy) {
        // 获取当前北京时间的毫秒级时间戳
        Instant currentInstant = Instant.now();
        if ("Korea".equals(proxy)) {
            // 将时间戳转换为韩国首尔时间的当天零点的毫秒级时间戳
            ZoneId seoulZone = ZoneId.of("Asia/Seoul");
            ZonedDateTime seoulDateTime = currentInstant.atZone(seoulZone).toLocalDate().atStartOfDay(seoulZone);
            long seoulZeroTimestampMillis = seoulDateTime.toInstant().toEpochMilli();
            return seoulZeroTimestampMillis;
        } else {
            // 将时间戳转换为太平洋时间的当天零点的毫秒级时间戳
            ZoneId pacificZone = ZoneId.of("America/Los_Angeles");
            ZonedDateTime pacificDateTime = currentInstant.atZone(pacificZone).toLocalDate().atStartOfDay(pacificZone);
            long pacificZeroTimestampMillis = pacificDateTime.toInstant().toEpochMilli();
            return pacificZeroTimestampMillis;
        }
    }

    public static DayTimestamp getDayStartAndEndTimestamp(Long timestamp, String proxy) {
        DayTimestamp result = new DayTimestamp();
        // 获取当前北京时间的毫秒级时间戳
        if (timestamp == null) {
            timestamp = System.currentTimeMillis();
        }
        Instant currentInstant = Instant.ofEpochMilli(timestamp);
        if ("Korea".equals(proxy)) {
            result.setProxy("Korea");
            // 将时间戳转换为韩国首尔时间的当天零点的毫秒级时间戳
            ZoneId seoulZone = ZoneId.of("Asia/Seoul");
            LocalDateTime seoulDateTime = currentInstant.atZone(seoulZone).toLocalDateTime();
            LocalDateTime seoulStartOfDay = seoulDateTime.toLocalDate().atStartOfDay();
            LocalDateTime seoulEndOfDay = seoulStartOfDay.plusDays(1).minus(1, ChronoUnit.SECONDS);
            long seoulStartOfDayTimestamp = seoulStartOfDay.atZone(seoulZone).toInstant().toEpochMilli();
            long seoulEndOfDayTimestamp = seoulEndOfDay.atZone(seoulZone).toInstant().toEpochMilli();
            result.setStartOfDayTimestamp(seoulStartOfDayTimestamp);
            result.setEndOfDayTimestamp(seoulEndOfDayTimestamp);
        } else {
            result.setProxy("Remo");
            // 将时间戳转换为太平洋时间的当天零点的毫秒级时间戳
            ZoneId pacificZone = ZoneId.of("America/Los_Angeles");
            LocalDateTime pacificDateTime = currentInstant.atZone(pacificZone).toLocalDateTime();
            LocalDateTime pacificStartOfDay = pacificDateTime.toLocalDate().atStartOfDay();
            LocalDateTime pacificEndOfDay = pacificStartOfDay.plusDays(1).minus(1, ChronoUnit.SECONDS);
            long pacificStartOfDayTimestamp = pacificStartOfDay.atZone(pacificZone).toInstant().toEpochMilli();
            long pacificEndOfDayTimestamp = pacificEndOfDay.atZone(pacificZone).toInstant().toEpochMilli();
            result.setStartOfDayTimestamp(pacificStartOfDayTimestamp);
            result.setEndOfDayTimestamp(pacificEndOfDayTimestamp);
        }
        return result;
    }

    /**
     * 找到并返回下一个周五的日期字符串。
     *
     * @return 下一个周五的日期字符串,格式为 yyyy-MM-dd
     */
    public static String findNearestFriday() {
        LocalDate currentDate = LocalDate.now();
        DayOfWeek currentDayOfWeek = currentDate.getDayOfWeek();

        // 计算到下一个周五还有几天
        int daysUntilNextFriday = DayOfWeek.FRIDAY.getValue() - currentDayOfWeek.getValue();
        if (daysUntilNextFriday <= 0) {
            daysUntilNextFriday += 7; // 如果今天就是周五,则加一周
        }

        // 加上天数得到下一个周五的日期
        LocalDate nextFriday = currentDate.plusDays(daysUntilNextFriday);

        return nextFriday.toString(); // 返回格式化的日期字符串,格式为 yyyy-MM-dd
    }

    /**
     * 根据给定的日期字符串,获取该日期所在周的周一日期字符串。
     *
     * @param dateStr 日期字符串,格式为"yyyy-MM-dd"
     * @return 返回该日期所在周的周一日期字符串,格式也为"yyyy-MM-dd"
     */
    public static String getWeekStrByDayStr(String dateStr) {
        String dateValue = null;
        String week = DateUtils.getWeek(DateUtils.StringToDate(dateStr, "yyyy-MM-dd"));
        int interval = DateUtils.getIntervalFromMonday(week);
        if (interval == 0) {
            dateValue = dateStr;
        } else {
            dateValue = DateUtils.getBeforeOrAfterDateType(interval, dateStr, "yyyy-MM-dd", Calendar.DAY_OF_MONTH);

        }
        return dateValue;
    }

    /**
     * 获取给定日期是星期几。
     *
     * @param date 给定的日期
     * @return 返回给定日期是星期几,用英文缩写表示(例如:"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
     */
    public static String getWeek(Date date) {
        String[] weeks = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week_index < 0) {
            week_index = 0;
        }
        return weeks[week_index];
    }

    /**
     * 根据给定的星期几,计算距离周一的天数间隔。
     *
     * @param week 给定的星期几,用英文缩写表示(例如:"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
     * @return 返回距离周一的天数间隔,周一返回0,周二返回-1,周三返回-2,以此类推
     */
    public static int getIntervalFromMonday(String week) {
        if ("Tue".equals(week)) {
            return -1;
        } else if ("Wed".equals(week)) {
            return -2;
        } else if ("Thu".equals(week)) {
            return -3;
        } else if ("Fri".equals(week)) {
            return -4;
        } else if ("Sat".equals(week)) {
            return -5;
        } else if ("Sun".equals(week)) {
            return -6;
        }
        return 0;
    }

    /**
     * 根据给定的月份字符串,获取该月份所在的季度字符串。
     *
     * @param dateStr 日期字符串,格式为"yyyy-MM"
     * @return 返回该月份所在的季度字符串,格式为"yyyy-MM",其中MM为季度的起始月份
     */
    public static String getQuarterStrByMonthStr(String dateStr) {
        String dateValue = null;
        String subYear = dateStr.substring(0, 4);
        String monthStr = dateStr.substring(5);
        if ("01".equals(monthStr) || "02".equals(monthStr) || "03".equals(monthStr)) {
            dateValue = subYear + "-" + "01";
        } else if ("04".equals(monthStr) || "05".equals(monthStr) || "06".equals(monthStr)) {
            dateValue = subYear + "-" + "04";
        } else if ("07".equals(monthStr) || "08".equals(monthStr) || "09".equals(monthStr)) {
            dateValue = subYear + "-" + "07";
        } else if ("10".equals(monthStr) || "11".equals(monthStr) || "12".equals(monthStr)) {
            dateValue = subYear + "-" + "10";
        }
        return dateValue;
    }

    /**
     * 根据给定的时间戳、代理和类型,获取太平洋时间当天开始和结束的时间戳。
     *
     * @param timestamp 给定的时间戳,如果为null,则使用当前系统时间
     * @param proxy     代理类型,用于确定时区("Korea"表示韩国首尔时间,"其他"表示美国洛杉矶时间)
     * @param type      类型,用于确定返回当天开始时间戳还是结束时间戳("startTime"表示开始时间戳,"其他"表示结束时间戳)
     * @return 返回太平洋时间当天开始或结束的时间戳
     */
    public static Long getDayStartAndEndTimestamp(Long timestamp, String proxy, String type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 将时间戳转换为Date对象
        Date date = new Date(timestamp);
        //获取北京时间字符串
        String dateStr = sdf.format(date);
        // 获取当前北京时间的毫秒级时间戳
        if (timestamp == null) {
            timestamp = System.currentTimeMillis();
        }
        Instant currentInstant = Instant.ofEpochMilli(timestamp);
    }

    /**
     * 根据给定的日期字符串,获取太平洋时区该日期当天的开始时间戳(午夜00:00)。
     *
     * @param dateStr 日期字符串,格式为ISO 8601标准(例如:"2023-10-05")
     * @return 返回太平洋时区该日期当天的开始时间戳(以毫秒为单位)
     */
    public static long getPacificZoneStartTimestampByDateStr(String dateStr) {
        // 解析日期字符串为LocalDate对象
        LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ISO_LOCAL_DATE);

        // 指定目标时区为太平洋时区
        ZoneId pacificZone = ZoneId.of("America/Los_Angeles");

        // 创建ZonedDateTime对象,将日期和时间设为午夜(00:00)
        ZonedDateTime zonedDateTime = ZonedDateTime.of(date, LocalTime.MIDNIGHT, pacificZone);

        // 转换为Instant对象(获取时间戳)
        Instant instant = zonedDateTime.toInstant();
        long timestamp = instant.toEpochMilli();
        return timestamp;
    }
}

咱们继续学Java——高级篇 第九十六篇:之Java 8日期时间API(本地时间与时区时间) 哈喽,各位Java编程爱好者们!在之前对Java 8日期时间API的学习中,我们已经了解了时间线(`Instant`)、本地日期(`LocalDate`)和日期调整器(`TemporalAdjusters`)等相关知识。今天,我们将继续深入学习该API中的本地时间(`LocalTime`)和时区时间(`ZonedDateTime`)部分。我希望通过这篇博客,用通俗易懂的语言为大家详细讲解这两个概念的特点、用法以及它们在实际应用中的重要性。在处理日常时间相关的操作以及涉及不同时区的业务场景时,正确理解和使用本 阅读详情

相关推荐

Java中日期与时间处理报错的调试

Java中日期与时间处理报错是一个常见的问题,但通过了解常见报错原因和调试方法,开发者可以快速定位和解决问题。在处理日期与时间时,尽量使用java.time包中的类,它们提供了更清晰、更灵活、更安全的API。同时,结合日志记录、单元测试、调试器和在线工具等调试工具和技巧,可以进一步提高调试效率。希望本文介绍的调试方法能帮助开发者更好地处理Java中的日期与时间问题。

shejizuopin的博客 1409

JAVA日期格式获取教程:掌握JAVA日期处理的精髓

JAVA日期格式获取教程:掌握JAVA日期处理的精髓 去发现同类优质开源项目:https://gitcode.com/ 在软件开发中,日期处理是常见且重要的功能之一。今天,我将向您推荐一个实用的开源项目——JAVA日期格式获取教程,该项目详细介绍了JAVA中获取日期及时间范围的方法。以下是对该项目的详细介绍和技术分析。 项目介绍 JAVA日期格式获取教程是一份详尽的文档,旨在帮助开发者理解并掌握如...

gitblog_06777的博客 794

Java 8 LocalDate实战:从基础创建到复杂业务日期处理

本文深入探讨Java 8 LocalDate的实战应用,从基础创建到复杂业务日期处理。通过丰富的代码示例,详细介绍日期比较、计算、格式化及进阶业务处理技巧,帮助开发者高效解决实际项目中的日期问题。特别强调LocalDate的不可变性、ISO-8601标准支持及多国日期格式化处理,是Java开发者必备的日期处理指南。

weixin_30582943的博客 295

日期格式统一处理

扩展SpringMVC的消息转换器,统一对日期类型进行格式处理。

cyt涛的博客 1979

Java业务标志处理实践:物流场景中的字段管理

实现类型安全的字段处理保证业务规则的强制约束提高代码可维护性方便后续扩展(如增加新的船状态)建议在实际开发中结合Spring框架的验证机制和JPA的审计功能,构建完整的业务处理流水线。这篇技术文章通过分层解耦的设计,既满足了当前业务需求,也为后续扩展保留了空间。开发者可根据具体业务场景调整状态机实现和校验规则。学习教程(传送门)1、掌握JAVA入门到进阶知识(持续写作中……2、学会Oracle数据库用法(创作中……3、手把手教你vbs脚本制作(完善中……4、牛逼哄哄的。

王大师企业官方博客 1361

Java日期时间处理技术深度解析

在深入探讨类的详细使用之前,让我们先来简要回顾一下Java中处理日期和时间所走过的历程。Java的Date类从Java 1.0版本起就存在于java.util包中,它一直是处理日期时间的标准类,尽管随着Java 8的发布,出现了更为强大和灵活的java.time包,但Date类在很多旧系统中仍有广泛应用。接口的设计初衷是为了提供一种通用的、可扩展的日期过滤机制,以便在不同的业务场景中对日期数据进行筛选。

weixin_36282234的博客 1003

java中的日期处理

在学习java的时候往往很多教材都忽视了这个问题,日期处理其实在挺重要的一个知识点。遇到几个朋友反复问到。就给写出来吧。。希望有遇到这个问题的可以参考一下。。其实在java的日期处理,大多数也都是在数据库开发应用的时候遇到的。主要就是下面的两个类吧。java.util.Date     |java.sql.Date    它的很多日期处理方法都过时了。被Calendar类中的方法替换1

XueJiang's Blog 684

掌握Joda-Time:Java日期时间处理高级指南

在本章中,我们将深入了解Joda-Time库,它是Java领域中用于日期和时间处理的流行库之一。Joda-Time自2002年起便由Stephen Colebourne贡献给开源社区,其不仅为Java的日期和时间处理提供了丰富而强大的API,还为Java 8中引入的新的日期时间API提供了灵感。DateTime类是 Joda-Time 中最常用的类之一,它能够表示一个具体的时刻,包括日期和时间。该类是不可变的,这意味着一旦创建,其值就不能被改变。

weixin_36073714的博客 1014

日期时间处理这么麻烦,为什么 Java 8 才终于搞清楚了?

LocalDateLocalDate如果你觉得这篇文章对你有帮助,或者有任何想法、建议,欢迎在评论区留言交流!我是一个在代码世界里不断摸索的小码农,愿我们都能在成长的路上越走越远,越学越强!

欢迎来到菜鸟不学编程的博客 1144

11-4 AEB 算法原理及系统组成

本专题旨在探讨如何利用仿真软件开发自动紧急制动系统AEB,主要通过整理开发流程,实现从需求到验证的全流程掌握,为后续开发提供支持;同时,研究了如何在汽车自动驾驶仿真工具中开发自己的算法,并解决了从ISO、E-CNAP、GB/T以及交通法规等提炼出功能需求的问题,以快速实现原型模型的开发。本专题重点讲解了AEB的工作原理、系统/软件架构和需求、算法模型及实现、CCRs/CCRb/CCRm建模与仿真、VRU-AEB-B/P/M建模与仿真,同时还提供了测试用例,期待将AEB算法成功地产品化。

AIgraphX 8548

整理的15个公开且可直接使用的电力视觉输电线路领域数据集

而巡检数据是目前来说影响我们做科研的最大阻碍,为此本内容主要总结了,现有的且公开免费的巡检数据集,供大家使用。STN PLAD数据集133个航拍图像,五个电力部件:电力塔及其塔的ID、绝缘子,防震锤,联板(yoke),图像的尺寸在5472×3648到5472×3078。IDID数据集:2000张图像,包含三个类别,正常绝缘子,破损绝缘子和闪络绝缘子三个类别,用于目标检测的实验。TTPLA数据集,用于实例分割,1100张尺寸为3840×2160,包含两个类别,电力杆塔和电力线。主要用于电力杆塔的目标检测。

weixin_42048361的博客 5010

java明天日期

我整理的一些关于【Java】的项目学习资料(附讲解~~)和大家一起分享、学习一下:https://d.51cto.com/bLN8S1Java中的日期处理:如何获取明天的日期 日期与时间在编程中是一个十分重要的主题。特别是在进行数据处理、计算以及时间相关的任务时,准确地处理日期是至关重要的。在Java中,处理日期和时间变...

weixin_37045116的博客 730

Vivado实战:从零封装AXI-Lite接口的呼吸灯IP核

本文提供了一份详细的Vivado实战指南,手把手教你如何将Verilog编写的呼吸灯模块封装成带AXI-Lite接口的IP核。内容涵盖从创建IP框架、编写核心逻辑、连接AXI总线到在ZYNQ系统中调用并编写C程序进行软硬件协同测试的完整流程,是掌握FPGA软硬件协同设计的关键实践。

weixin_29233333的博客 596

Java POI导出Excel:30个复杂场景实战大揭秘

Java POI 导出 Excel 实战指南 本文深入探讨了 Java 开发中使用 POI 库导出 Excel 的 30 个实战场景,涵盖了从基础操作到高级应用的各个方面。主要内容包括: 基础功能实现 数据库数据导出 单元格样式设置 合并单元格 列宽行高调整 数据格式化 复杂数据处理 多 Sheet 导出 动态表头生成 树形结构导出 分组数据展示 大数据量分页导出 特殊格式处理 图片插入 超链接添加 公式计算 批注说明 富文本显示 系统集成方案 数据库直接导出 SpringBoot 集成 MyBatis 整

m0_73978383的博客 1517

OJ(while+cin.get()判断结束)

今天要记录一道看起来十分简单的OJ题目,但开始对于cin的一些操作忘得差不多了,没做出来,故记下来给自己提个醒。 描述 给出包含N个单词的一行输入,输出N行。第一行和输入一样。每次输出过一行后,这一行的第一个单词在下一行被放到最后。 输入 包含N个单词的字符串,单词以一个空格分开。N不在输入中给出,你需要计算单词的数量来获得。字符串包含的字符数小于100。 输出 输出N行。...

Stark_JC的博客 2357

10位PWM能否满足电梯±5mm平层精度?4位扩展法让10位PWM达到14位精度

电梯平层精度直接关系乘坐舒适性与安全性,而PWM分辨率是决定精度的关键因素之一。10位PWM能否满足±5mm的平层精度要求?本文从分辨率与物理量的对应关系出发,结合工程精度需求与实战对比,给出明确的选型结论与解决方案,请参考优快云博客《4位扩展法:基于ATtiny816的高精度PWM软件扩展方法》和《低成本高精度PWM:4位扩展法原理、实现和工程实践》。10位PWM的分辨率为 $2^{10} = 1024$ 级。

m0_73354873的博客 243

java localdate日期格式处理

引言 作为一种业务场景,我们经常会从前端取到日期数据,针对前端回传的数据再到数据库进行取值。那么针对前端传回来的日期数据可能有几种情况,我们也要做对应的处理。 日期的表现形式有很多种,在java里我们可以把类似于20180630 这一种看成是一种int的,也可以看成是string类型的,具体则要看我们的业务需求,如果是数据传过来不用进行例如日期变化之类的处理我建议存int 类型。如果是要对日期...

与望 7625

三维重建笔记_光束平差法(Bundle Adjustment, BA)

目录 1 光束平差法(Bundle Adjustment, BA) 1.1 SFM (Structure‐from‐Motion) 定义 问题描述 1.2 重投影误差 (Reprojection Error) 目标函数 1.3 使用 Levenberg‐Marquardt Algorithm 进行优化 问题描述 简化目标函数 参考 Gauss‐Newton Method ...

惊鸿一博 2万+

用数字求日期java,Java实用经验总结--日期、数字篇

Java实用经验总结--日期、数字篇1.日期部分对于像日期、时间和钱这样的对象来说,不同的国家、地区都有不同的显示格式。即便是同一地区,也可能存在差异。但是在不考虑国家化,时间格式相对固定的情形下,对于时间的处理还是相对比较简单的。在我最近所作的一个小程序里面,遇到了一些与日期有关的且不考虑国际化和复杂格式的问题。例如如何求两个日期所差的天数,所差的月数;将日期类转化为规定格式的字符串,将规定格式...

weixin_39815943的博客 348

STM32F103 RTC闹钟唤醒Stop模式的EXTI17中断实现

本文详细介绍了STM32F103如何通过RTC闹钟触发EXTI17中断实现从Stop模式的高效唤醒。针对低功耗应用场景,提供了完整的硬件配置、CubeMX设置及代码实现方案,包括时间格式转换、中断处理和功耗优化技巧,帮助开发者可靠实现定时唤醒功能。

ol78901234的博客 230

C# 与欧姆龙 PLC 实战:通过 Ethernet/IP 协议进行设备控制与监控

本文介绍了如何通过C#和Ethernet/IP协议实现与欧姆龙PLC的通信。Ethernet/IP是基于以太网的工业协议,适用于工业设备间的实时数据交换。文章详细讲解了使用EthernetIPSharp库建立连接、读写数据的步骤,并提供了示例代码。此外,还探讨了实时监控、报警系统等高级功能,为工业自动化控制系统开发提供了实用指导。该方法简化了PLC通信开发,提高了系统可靠性和智能化程度。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 811

JAVA后端开发—— 深入解析JSON、Java与数据库中的日期时间处理

任何语言都能轻松处理字符串。

tybAly的博客 1025

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

Java 日期时间处理全面解析

Java 日期时间处理是编程中常见的需求,尤其是在涉及数据记录、时间戳、日历事件等场景时。Java 提供了多种方式来处理日期和时间,包括传统的和类,以及 Java 8 引入的新的日期时间 APIjava.time。本文将全面解析 Java 日期时间处理的各种方法,并比较它们的优缺点。

lsx202406的博客 437

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

Java日期时间处理常见错误与bug及解决方案详解

Java日期时间处理常见问题及解决方案 摘要:Java日期时间处理中存在时区处理、日期计算、格式解析等常见问题。时区问题可通过显式指定时区和使用Java 8的ZonedDateTime解决;日期计算应优先使用Java 8的不可变API并正确处理边界情况;格式解析要注意线程安全问题和宽松解析模式。最佳实践包括:始终显式指定时区、使用Java 8日期API、区分不同时间单位、采用严格解析模式。新版java.time包提供了线程安全且设计良好的日期时间处理方案,应优先使用。

本博客聚焦 YOLOv11 全流程落地,涵盖架构优化、数据集处理、训练技巧与多场景部署,兼及国产数据库、Java 开发与 AI 模型应用,内容兼顾理论与工程实践,为开发者提供系统干货,助力高效提升技术能力。 1199

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

为什么 Java 中的时间类如此繁多而复杂?

旧的 API 设计缺陷:早期的Date和Calendar类存在诸多问题,导致需要新的 API 来替代它们。时间处理的本质复杂性:时区、日历系统、时间精度等因素使得时间处理本身就很复杂。Java 8java.timeAPI 的细分设计:为了应对不同的需求,Java 8 将时间处理类划分得更加细致,确保在各类场景下都能有最合适的类可用。向后兼容性与现代化需求的权衡:Java 保留了旧的时间类,同时提供现代化的 API 来解决新的需求。灵活性与可扩展性。

ahauedu的专栏 1205

Java 日期与时间的处理

获取当前时间戳(毫秒)

jiaworld的博客 221
上一篇: 不会实现验证码短信发送?教你对接阿里云短信服务(干货)
下一篇: 集成MeetBot官方API给订单用户发送WhatsApp消息
知了蝉
博客等级 码龄10年 350粉丝 43原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知了蝉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值