问题描述
我正在解析一个用逗号分隔的文件,其中有两个字段需要转换为时间戳。我得到一个日期,并且一个单独的字段使我在午夜过去了几分钟...例如:
2020/10 / 15,360
现在,在大多数情况下,360将是上午6点(360/60 = 6),但DST表示可能是5或7。问题是,即使是DST天,我总是希望输出6am。
Calendar cal = Calendar.getInstance();
cal.setTime(schedDate);
cal.add(Calendar.MINUTE,Integer.parseInt(minutes));
return new Timestamp(cal.getTimeInMillis());
cal.set(cal.DST_OFFSET,0);
但这似乎无法解决问题。我不确定日历是否具有禁用DST偏移量的内置功能,但是任何建议都会受到赞赏
解决方法
使用MyOptions.MyString
,它不必处理时区(因此也可以处理DST)。请注意,MyOptions.MyString.Value
是the modern date-time API的一部分。
LocalDateTime
输出:
LocalDateTime
我还建议您停止使用容易出错且过时的import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime ldt = LocalDate.parse("10/15/2020",DateTimeFormatter.ofPattern("M/d/u")).atStartOfDay()
.plusHours(6);
System.out.println(ldt);
}
}
日期时间API。
如果您正在为自己的Android项目执行此操作,并且您的Android API级别仍不符合Java-8,请选中Java 8+ APIs available through desugaring和How to use ThreeTenABP in Android Project。
通过 Trail: Date Time 了解有关现代日期时间API的更多信息。
,使用java.time
,您可以涉及系统的时区,也可以为其指定固定的时区。
以下代码显示了如何执行此操作:
public static void main(String[] args) {
// example input
String date = "10/15/2020";
long minutes = 360;
// create a LocalDate from the String considering its format
LocalDate localDate = LocalDate.parse(date,DateTimeFormatter.ofPattern("MM/dd/uuuu"));
// create a minimum LocalTime (the beginning of a day) and add the minutes you got
LocalTime timeOfDay = LocalTime.MIN.plusMinutes(minutes);
// create a zone-aware object by using the date,the time of day and the system's zone
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDate,timeOfDay,ZoneId.systemDefault());
// print the toString() method (implicitly)
System.out.println(zonedDateTime);
// or use a custom format
System.out.println(zonedDateTime.format(DateTimeFormatter
.ofPattern("MM/dd/uuuu HH:mm:ss")));
}
它输出以下内容(在具有UTC + 2的系统上运行):
2020-10-15T06:00+02:00[Europe/Berlin]
10/15/2020 06:00:00
,
现在,我们可以让java.time解析CSV文件(逗号分隔值文件)中的两个字段,并将它们组合:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("M/d/u");
DateTimeFormatter minuteOfDayFormatter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.MINUTE_OF_DAY)
.toFormatter();
String dateString = "10/15/2020";
String timeString = "360";
LocalDate date = LocalDate.parse(dateString,dateFormatter);
LocalTime time = LocalTime.parse(timeString,minuteOfDayFormatter);
LocalDateTime dateTime = date.atTime(time);
System.out.println(dateTime);
输出为:
2020-10-15T06:00
如果您认为您的SQL数据库需要java.sql.Timestamp
,则很可能不需要。您可以使用LocalDateTime
将PreparedStatement.setObject()
对象传递到数据库。如果您需要控制时区(通常是个好主意),请先将其转换为OffsetDateTime
或Instant
。搜索方式。