Java 将系统时间转换为字符串到时间戳
我正在尝试使用Java获取计算机的时间,并使用Java 将系统时间转换为字符串到时间戳,java,date,timestamp,simpledateformat,time-format,Java,Date,Timestamp,Simpledateformat,Time Format,我正在尝试使用Java获取计算机的时间,并使用SimpleDataFormatobject按特定顺序格式化,但它不会格式化;请帮忙 这是我的代码: java.util.Date parsedDate = null; try { DateFormat dateFormat = new SimpleDateFormat("HH:mm"); parsedDate = dateFormat.parse(dateFormat.format(new java.util.
SimpleDataFormat
object按特定顺序格式化,但它不会格式化;请帮忙
这是我的代码:
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());
使用:
嗨,用户8545027,我对你的代码做了一点修改,现在对我有用了。我还使用ThreadLocal使SimpleDataFormat对多线程安全
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());
}
}
package com.java;
导入java.text.simpleDataFormat;
导入java.util.Date;
公开课考试{
private ThreadLocal threadSafeDateFormat=new ThreadLocal(){
@凌驾
受保护的SimpleDataFormat初始值(){
返回新的SimpleDataFormat(“HH:mm”);
}
};
字符串格式化日期(){
SimpleDataFormat=threadSafeDateFormat.get();
String timeStamp=format.format(new Date());
返回时间戳;
}
公共静态void main(字符串[]args){
测试=新测试();
System.out.println(test.formatDate());
}
}
如果有任何问题,请告诉我。希望这有帮助。tl;博士
java.time
您使用的是现在已被现代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 ) ;
对于其他格式,请使用DateTimeFormatter
DateTimeFormatter f = DateTimeFormatter.ofPattern( "HH:mm" ) ;
String output = lt.format( f ) ;
所有这些都在堆栈溢出时处理过多次。搜索更多信息和讨论 我看不出有什么区别。你从你计算机上的两行代码中得到两个不同的结果吗?使用上面的代码,我得到的结果是“1970-01-01 21:49:00.0”,希望这就是你要找的。它不起作用,我要找的结果是21:49仍然是相同的结果“1970-01-01 08:49:00.0”我告诉过你我没有得到的结果是我得到了:“1970-01-01 08:49:00.0”我只想要以下格式的时钟:“08:44”->“HH:mm”(1)请具体说明期望的结果以及观察到的结果的差异。(2)不要接受异常。这一个特别可能会给我们提供有关出错原因的重要信息。(3)
SimpleDateFormat
早已过时,而且不是那么麻烦。我建议改为时间戳
没有也不能保存格式。它只是一个时间点。永远不要编写空的catch块。异常会告诉您出了什么问题,如果忽略它们,会使代码的故障排除变得极其困难。至少,catch块需要显示堆栈跟踪,例如使用e.printStackTrace()
。
List<LocalTime> times = new ArrayList<>() ;
times.add( lt ) ;
…
Collections.sort( times ) ;
String output = lt.toString() ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "HH:mm" ) ;
String output = lt.format( f ) ;