问题描述
问题:
我需要在sqlITE数据库(Android)中保存一个时间戳,并从中提取日期。最好的方法是LocalDateTime
或Instant.Now()
?因为该Android应用程序已在沙特阿拉伯使用。
要求:
我必须在“时间戳”列中查询在数据库中输入的第一个时间戳,并从中单独提取日期,以将其与当前日期进行比较,以检查日期差是否超过30天。
需要帮助:
到目前为止:
我曾经使用LocalDateTime
保存时间戳,但不确定如何仅从中提取日期。
解决方法
您可以使用此功能(适用于Api 26 +):
String ts = String.valueOf(Instant.now().getEpochSecond());
支持较早的Android版本:
String ts = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
或者,如果您希望以特定日期格式使用它,请使用以下命令:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String millisInString = dateFormat.format(new Date());
,
以下是您要的全部信息:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
// The current moment at UTC time-scale
Instant now = Instant.now();
System.out.println(now);
// The number of milliseconds from the epoch of 1970-01-01T00:00:00Z.
long millis = now.toEpochMilli();
System.out.println(millis);
// The number of seconds from the Java epoch of 1970-01-01T00:00:00Z.
long seconds = now.getEpochSecond();
System.out.println(seconds);
// Zone ID of Saudi Arabia
ZoneId zoneId = ZoneId.of("Asia/Riyadh");
// Get ZonedDateTime from Instant
ZonedDateTime zdt = now.atZone(zoneId);
System.out.println(zdt);
// Get the LocalDateTime part of this ZonedDateTime
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
// Get the LocalDate part of this ZonedDateTime
LocalDate today = zdt.toLocalDate();
System.out.println(today);
// An instant in the past
Instant past = LocalDateTime.of(LocalDate.of(2020,Month.APRIL,10),LocalTime.MIDNIGHT)
.toInstant(ZoneOffset.ofHours(3));// Zone Offset of Saudi Arabia is UTC +3
System.out.println(past);
// No. of months
long months = ChronoUnit.MONTHS.between(past.atZone(zoneId),zdt);
System.out.println(months);
}
}
输出:
2020-08-27T08:45:31.927452Z
1598517931927
1598517931
2020-08-27T11:45:31.927452+03:00[Asia/Riyadh]
2020-08-27T11:45:31.927452
2020-08-27
2020-04-09T21:00:00Z
4