Java日期格式化:String.format()替代SimpleDateFormat
不想用SimpleDateFormat?试试String.format()格式化Java日期!
SimpleDateFormat虽然方便,但它并非线程安全的。如果你需要一个线程安全的日期格式化方法,可以考虑使用String.format()。
String.format()如何工作?
- 将Date对象转换为long类型的时间戳 (从1970年1月1日起的毫秒数)。2. 使用String.format()和特定的格式化转换说明符来格式化时间戳。
**示例代码:**javaimport java.util.Date;
public class DateFormatExample { public static void main(String[] args) { Date date = new Date(); long timestamp = date.getTime(); String formattedDate = String.format('Formatted Date: %tF %tT', timestamp, timestamp); System.out.println(formattedDate); }}
代码解释:
date.getTime(): 获取日期的long型时间戳。*%tF: 格式化为日期 (YYYY-MM-DD)。*%tT: 格式化为时间 (HH:MM:SS)。
优点:
- 线程安全。
缺点:
- 相比SimpleDateFormat,代码可能更繁琐。* 需要手动处理日期和时间的格式化。
总结:
String.format()提供了一种线程安全的日期格式化方法,但在易用性方面略逊于SimpleDateFormat。选择哪种方法取决于你的具体需求。
原文地址: https://www.cveoy.top/t/topic/iyU 著作权归作者所有。请勿转载和采集!