如何将包含 HH:mm:ss 的 SimpleDateFormat 中的日历对象设置为当前日期但时间

How to set Calendar object to current date but time from SimpleDateFormat that contains HH:mm:ss

我需要创建一个包含当前日期的新 Calendar 对象,但需要根据格式为 HH:mm:ss.

的给定字符串设置时间

我创建了一个包含当前日期和时间的新日历对象,然后使用 SimpleDateFormat 对象解析字符串并设置该字符串的时间,但这只会用解析的时间和 Jan 覆盖日历对象1 1970 年:

def currentTime = new java.util.Date();
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(currentTime);
java.util.Date inTime = new SimpleDateFormat("HH:mm:ss").parse(initialTime);
calendar1.setTime(inTime);

有没有办法从日期对象中获取小时、分钟、秒和毫秒的值,以便与 calendar.set(Calendar.HOUR_OF_DAY, hour) 等一起使用?

Calendar objet Time 是具有标准格式的 java.util.Date 对象。您不能为您的日历设置特定格式的日期。

要获取日期详细信息(小时、分钟...),请尝试:

    final Date date = new Date(); // your date
    final Calendar cal = Calendar.getInstance();
    cal.setTime(date);

    final int year = cal.get(Calendar.YEAR);
    final int month = cal.get(Calendar.MONTH);
    final int day = cal.get(Calendar.DAY_OF_MONTH);
    final int hour = cal.get(Calendar.HOUR_OF_DAY);
    final int minute = cal.get(Calendar.MINUTE);
    final int second = cal.get(Calendar.SECOND);

不确定这是否对您有帮助。

    String hhmmss = "10:20:30";
    String[] parts = hhmmss.split(":");
    Calendar cal = Calendar.getInstance();      
    cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parts[0]));
    cal.set(Calendar.MINUTE, Integer.parseInt(parts[1]));
    cal.set(Calendar.SECOND, Integer.parseInt(parts[2]));

tl;博士

GregorianCalendar.from(                   // Converting from modern java.time class to troublesome legacy class. Do so only if you must. Otherwise use only the java.time classes.
    ZonedDateTime.of(                     // Modern java.time class representing a moment, a point on the timeline, with an assigned time zone through which to see the wall-clock time used by the people of a particular region. 
        LocalDate.now( ZoneId.of( “Pacific/Auckland” ) ) ,   // The current date in a particular time zone. For any given moment, the date varies around the globe by zone. 
        LocalTime.of( 12 , 34 , 56 ) ,    // Specify your desired time-of-day. 
        ZoneId.of( “Pacific/Auckland” )   // Assign a time zone for which the date and time is intended. 
    )
)

java.time

现代方法使用 java.time 类。

ZoneId z = ZoneId.of( “America/Montreal” ) ;
LocalDate ld = LocalDate.now( z ) ;
LocalTime lt = LocalTime.of( 12 , 34 , 56 ) ;  // 12:34:56
ZonedDateTime zdt =  ZonedDateTime.of( ld , lt , z ) ;

您可以从现有 ZonedDateTime 中提取时间(或日期)。

LocalTime lt = zdt.toLocalTime() ;
LocalDate ld = zdt.toLocalDate() ;

最好避免在 Java 8 之前添加的麻烦的旧旧日期时间 类。但如果必须,您可以在现代和旧版之间转换 类。调用添加到旧 类 的新方法。

GregorianCalendar gc = GregorianCalendar.from( zdt ) ;  // If you must, but better to avoid the troublesome old legacy classes.