向日期对象添加小时和分钟

时间:2018-12-10 21:02:18

标签: java date javafx datepicker

我有一个小gui,其中有一个日期选择器和一个用于输入时间(HH:mm)的文本框。

我想创建一种方法,从日期选择器中获取日期,并将时间(HH:mm)添加到日期选择器日期,然后返回日期,以便将其保存在数据库中。

我希望使用“ yyyy-MM-dd HH:mm”格式的最终​​日期

这是我尝试过的:

public Date getCalibrationDate(){
        String time = getTime();
        int hours = Integer.parseInt(time.substring(0,2));
        int minutes = Integer.parseInt(time.substring(2,4));
        Date date = java.sql.Date.valueOf(kalibreringsdatum.getValue());

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        calendar.set(Calendar.HOUR_OF_DAY, hours);
        calendar.set(Calendar.MINUTE,minutes);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String dateAsString = sdf.format(calendar.getTime());
        Date dateTime = null;

        try {
            dateTime = sdf.parse(dateAsString);
        } catch (ParseException e) {
            System.out.println("Could not parse date");
            e.printStackTrace();
        }
        return dateTime;
    }

但是它以这种方式返回日期:CET 2018年12月11日星期二11:22:00。 我在做什么错,如何简化该方法?

2 个答案:

答案 0 :(得分:3)

tl; dr

对于类型为TIMESTAMP WITHOUT TIME ZONE的数据库列。

myPreparedStatement                        // As of JDBC 4.2, send/receive java.time objects to/from your database.
.setObject(                                // Call `PreparedStatement::setObject` and `ResultSet::getObject` for java.time objects.
    … ,                                    // Fill-in to indicate which placeholder in SQL statement.
    LocalDateTime.of(                      // Represent a date with time-of-day, but lacking in zone/offset so NOT a moment, NOT a point on the timeline.
        LocalDate.parse( "2018-01-23" ) ,  // Parse the date-only value.
        LocalTime.parse( "21:54" )         // Parse the time-of-day.
    )                                      // Returns a `LocalDateTime` object.
)

对于类型为TIMESTAMP WITH TIME ZONE的数据库列。

myPreparedStatement                        // As of JDBC 4.2, send/receive java.time objects to/from your database.
.setObject(                                // Call `PreparedStatement::setObject` and `ResultSet::getObject` for java.time objects.
    … ,                                    // Fill-in to indicate which placeholder in SQL statement.
    LocalDateTime.of(                      // Represent a date with time-of-day, but lacking in zone/offset so NOT a moment, NOT a point on the timeline.
        LocalDate.parse( "2018-01-23" ) ,  // Parse the date-only value.
        LocalTime.parse( "21:54" )         // Parse the time-of-day.
    )                                      // Returns a `LocalDateTime` object.
    .atZone(                               // Assign a time zone to make a moment.
        ZoneId.of( "Pacific/Auckland" )    // Real time zones have a proper name in `Continent/Region` format. Never use 2-4 letter pseudo-zones such as `PDT`, `IST`, `CST`, etc. 
    )                                      // Returns a `ZonedDateTime` object.
    .toOffsetDateTime()                    // Strip out the time zone, leaving only a mere offset-from-UTC (a number of hours-minutes-seconds). Returns a `OffsetDateTime` object.
    .withOffsetSameInstant(                // Adjust the offset-from-UTC to UTC itself (an offset of zero). Same moment, different wall-clock time.
        ZoneOffset.UTC 
    )                                      // Returns another `OffsetDateTime` object.
)

java.time

现代方法使用了几年前的 java.time 类,这些类取代了可怕的旧遗留类(CalendarDateSimpleDateFormat等)

LocalDate

LocalDate类表示没有日期,没有time zoneoffset-from-UTC的仅日期值。

文本中仅日期值的通用SQL格式为YYYY-MM-DD。这也是ISO 8601标准定义的格式。解析/生成字符串时, java.time 类默认使用ISO 8601格式。因此,无需指定格式设置模式。

LocalDate ld = LocalDate.parse( "2018-01-23" ) ;

类似于一天中小时和分钟的HH:MM格式的字符串。

LocalTime lt = LocalTime.parse( "21:54" ) ;

将日期与时间结合起来。

LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;
  

ldt.toString():2018-01-23T21:54

请注意,LocalDateTime是故意缺少时区或从UTC偏移的概念,不是 片刻,不是 点在时间轴上。因此,仅适合将类似于SQL标准TIMESTAMP WITHOUT TIME ZONE的数据类型的列保存到数据库。

JDBC 4.2

从JDBC 4.2开始,我们可以通过setObjectgetObject与数据库直接交换 java.time 对象。

myPreparedStatement.setObject( … , ldt ) ;

检索。

LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;

ZonedDateTime

如果要处理时间线上的时间点,实际点,请使用适当的Java类(InstantOffsetDateTimeZonedDateTime)。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

OffsetDateTime

现在我们有片刻。通常,在移动日期(例如转移到数据库)时,最好专注于UTC。

OffsetDateTime odtUtc = zdt.toOffsetDateTime().withOffset( ZoneOffset.UTC ) ;

发送到数据库。

myPreparedStatement.setObject( … , odtUtc ) ;

检索。

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

关于 java.time

java.time框架已内置在Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendarSimpleDateFormat

目前位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解更多信息,请参见Oracle Tutorial。并在Stack Overflow中搜索许多示例和说明。规格为JSR 310

您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*类。

在哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展了java.time。该项目为将来可能在java.time中添加内容提供了一个试验场。您可能会在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

答案 1 :(得分:0)

您可以使用SimpleDateFormat获得所需的内容:

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateAndTime {

public static void main(String[] args) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
    System.out.println(sdf.format(new Date()))
}
}
相关问题