当前位置: 代码迷 >> 综合 >> DateTimeFormatter 时间戳与String类型日期/时间互转
  详细解决方案

DateTimeFormatter 时间戳与String类型日期/时间互转

热度:40   发布时间:2024-01-21 18:08:04.0
 /*** 时间戳转日期/时间** @param seconds 时间戳* @param pattern 时间格式* @return 格式化的时间*/@RequiresApi(api = Build.VERSION_CODES.O)public static String timeStamp2Date(long seconds, String pattern) {String time = "暂无数据";if (TextUtils.isEmpty(pattern)) pattern = "yyyy-MM-dd  HH:mm:ss";LocalDateTime dateTime = LocalDateTime.ofEpochSecond(seconds / 1000L, 0, ZoneOffset.ofHours(8));if (seconds != 0) time = dateTime.format(DateTimeFormatter.ofPattern(pattern));return time;}/*** 日期/时间转时间戳* @param date 时间* @param pattern 时间格式* @return  时间戳*/@RequiresApi(api = Build.VERSION_CODES.O)public static long date2TimeStamp(String date,String pattern) {long timeStamp ;if (TextUtils.isEmpty(pattern)) pattern = "yyyy-MM-dd  HH:mm:ss";DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);LocalDateTime localDateTime = LocalDateTime.parse(date,formatter);timeStamp = localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();LogUtils.i("String转时间戳" + timeStamp);return timeStamp;}

 

  相关解决方案