Android 中Sqlite数据库存日期long与字符串转换

以下是代码片段
model中

private long bindingTime;
private long completionTime;

long转日期字符串,使用Java8中的

long bindingTimeMillis = equipBind.getBindingTime();
if(bindingTimeMillis!=0)
{
      String bindingTimeStr = DateUtil.formatTimestamp(bindingTimeMillis, "yyyy-MM-dd HH:mm:ss");
      bindingTimeTextView.setText(bindingTimeStr);
}
   public static String formatTimestamp(long timestamp, String format) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        Date date = new Date(timestamp);
        return dateFormat.format(date);
    }

    public static long parseDateString(String dateString, String format) throws ParseException, ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        Date date = dateFormat.parse(dateString);
        return date.getTime();
    }

java8 LocalDateTime 写法

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.text.ParseException;

public class DateUtil {
    public static String formatTimestamp(long timestamp, String format) {
        Instant instant = Instant.ofEpochMilli(timestamp);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        return localDateTime.format(formatter);
    }

    public static long parseDateString(String dateString, String format) throws ParseException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        LocalDateTime localDateTime = LocalDateTime.parse(dateString, formatter);
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
        return instant.toEpochMilli();
    }
}
posted @ 2023-10-04 23:52  zhaogaojian  阅读(77)  评论(0编辑  收藏  举报