使用 SimpleDateFormat 格式化日期的 Java 程序
SimpleDateFormat 类用于解析和格式化日期。要创建一个对象,请首先导入以下包
import java.text.SimpleDateFormat;
设定日期
String strDate = "'Year = '"; strDate += "yyyy"; strDate += "'
Month = '"; strDate += "MMMMMMMMM"; strDate += "'
Hours = '"; strDate += "hh"; strDate += "a"; strDate += "'
Minutes = '"; strDate += "mm"; strDate += "'
Seconds = '"; strDate += "ss";
现在,创建一个对象并格式化日期 −
SimpleDateFormat dateFormat = new SimpleDateFormat(strDate); String formattedDate = dateFormat.format(new Date());
以下是一个示例 −
示例
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
public static void main(String args[]) {
String strDate = "'Year = '";
strDate += "yyyy";
strDate += "'
Month = '";
strDate += "MMMMMMMMM";
strDate += "'
Hours = '";
strDate += "hh";
strDate += "a";
strDate += "'
Minutes = '";
strDate += "mm";
strDate += "'
Seconds = '";
strDate += "ss";
System.out.println("Date and Time....");
SimpleDateFormat dateFormat = new SimpleDateFormat(strDate);
String formattedDate = dateFormat.format(new Date());
System.out.println(formattedDate);
}
}输出
Date and Time.... Year = 2018 Month = November Hours = 09AM Minutes = 12 Seconds = 41
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP