我需要创建一个包含当前日期的新Calendar
对象,但需要从给定的格式HH:mm:ss
字符串设置时间。
我使用当前日期和时间创建一个新的日历对象,然后使用SimpleDateFormat
对象来解析字符串并设置该时间的时间,但仅用解析的时间和1970年1月1日覆盖日历对象:
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);
有没有办法从Date对象中获取Hour,Minute,Seconds和Milliseconds的值,以便将它与calendar.set(Calendar.HOUR_OF_DAY, hour)
等一起使用?
答案 0 :(得分:2)
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类。
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.
答案 1 :(得分:0)
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);
答案 2 :(得分:0)
不确定这是否对您有所帮助。
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]));