在 Java 中编辑日期格式
在 Java 中,修改日期格式是一项常见任务。一个常见的要求是将日期从给定格式(例如 dd/MM/yyyy)转换为其他格式(例如 yyyy/MM/dd)。
解决方案:
要实现这种日期格式转换,可以利用Java的SimpleDateFormat class:
final String OLD_FORMAT = "dd/MM/yyyy"; final String NEW_FORMAT = "yyyy/MM/dd"; // Example date in old format: 12/08/2010 String oldDateString = "12/08/2010"; String newDateString; SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT); Date d = sdf.parse(oldDateString); sdf.applyPattern(NEW_FORMAT); newDateString = sdf.format(d); // Output: 2010/08/12 (date in new format)
此解决方案创建一个 SimpleDateFormat 对象并使用旧格式解析输入日期。然后,它应用新的格式模式并相应地格式化日期,从而产生所需的输出格式。
以上是如何更改 Java 中的日期格式?的详细内容。更多信息请关注PHP中文网其他相关文章!