我正在尝试使用Java来获取计算机的时间并使用SimpleDateFormat
对象按特定顺序对其进行格式化,但它不会格式化;请帮忙。
这是我的代码:
java.util.Date parsedDate = null;
try {
DateFormat dateFormat = new SimpleDateFormat("HH:mm");
parsedDate = dateFormat.parse(dateFormat.format(new java.util.Date()));
}catch(ParseException e){
}
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
LocalTime
.now( ZoneId.of( "Pacific/Auckland" ) )
.toString()
您正在使用现在由现代java.time类取代的麻烦的旧遗留类。完全避免使用旧课程。
获取UTC的当前时刻,分辨率最高可达纳秒。
Instant instant = Instant.now() ;
要通过特定区域的挂钟时间查看同一时刻,请应用时区。
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atone( z ) ;
要仅使用没有日期且没有时区的时间,请提取LocalTime
对象。
LocalTime lt = zdt.toLocalTime() ;
如果通过“格式到特定顺序”,则意味着排序......这些对象知道如何排序。不需要用于排序的字符串。
List<LocalTime> times = new ArrayList<>() ;
times.add( lt ) ;
…
Collections.sort( times ) ;
生成一个字符串以显示给用户。默认情况下,java.time类使用标准的ISO 8601格式来生成/解析字符串。
String output = lt.toString() ;
对于其他格式,请使用DateTimeFormatter
。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "HH:mm" ) ;
String output = lt.format( f ) ;
所有这些都已经在Stack Overflow上处理了很多次。搜索更多信息和讨论。
嗨user8545027我修改了你的代码,它现在对我有用。我还使用ThreadLocal使SimpleDateFormat对MultiThreading安全。
package com.java;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
private ThreadLocal<SimpleDateFormat> threadSafeDateFormat = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("HH:mm");
}
};
String formatDate() {
SimpleDateFormat format = threadSafeDateFormat.get();
String timeStamp = format.format(new Date());
return timeStamp;
}
public static void main(String[] args) {
Test test = new Test();
System.out.println(test.formatDate());
}
}
如果有任何问题,请告诉我。希望这可以帮助。
使用:
public class Basics {
public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("HH:mm");
String date = dateFormat.format(System.currentTimeMillis());
System.out.println(date);
}
}