Java程序使用SimpleDateFormat格式化日期
SimpleDateFormat类用于解析和格式化日期。要创建一个对象,首先导入以下包
import java.text.SimpleDateFormat;
设置日期
String strDate = "'Year = '"; strDate += "yyyy"; strDate += "'\nMonth = '"; strDate += "MMMMMMMMM"; strDate += "'\nHours = '"; strDate += "hh"; strDate += "a"; strDate += "'\nMinutes = '"; strDate += "mm"; strDate += "'\nSeconds = '"; 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 += "'\nMonth = '";
strDate += "MMMMMMMMM";
strDate += "'\nHours = '";
strDate += "hh";
strDate += "a";
strDate += "'\nMinutes = '";
strDate += "mm";
strDate += "'\nSeconds = '";
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
热门推荐
10 小学立秋祝福语大全简短
11 升职加薪的祝福语简短
12 弟弟考上军校祝福语简短
13 对新人祝福语大全简短
14 男生节搞笑简短祝福语
15 牛年祝福语简短搞笑的
16 紫玫瑰生日祝福语简短
17 祝福语签名简短霸气女生
18 牛年祝福语简短走心