java时间格式如何设置

44次阅读
没有评论

共计 753 个字符,预计需要花费 2 分钟才能阅读完成。

在 Java 中,你可以使用 SimpleDateFormat 类来设置日期和时间的格式。下面是一些常见的日期和时间格式的设置示例:

  1. 设置日期的格式:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// 获取当前日期并按指定格式输出
String formattedDate = dateFormat.format(new Date());
System.out.println(formattedDate); // 输出:2022-01-01
  1. 设置时间的格式:
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
// 获取当前时间并按指定格式输出
String formattedTime = timeFormat.format(new Date());
System.out.println(formattedTime); // 输出:12:34:56
  1. 设置日期和时间的格式:
SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 获取当前日期和时间并按指定格式输出
String formattedDateTime = dateTimeFormat.format(new Date());
System.out.println(formattedDateTime); // 输出:2022-01-01 12:34:56

你可以根据自己的需求来调整日期和时间格式中的格式字符串,例如使用 "MM" 表示月份,使用 "dd" 表示日期,使用 "HH" 表示 24 小时制的小时,使用 "mm" 表示分钟,使用 "ss" 表示秒等。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-22发表,共计753字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)