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 生日广州男生祝福语简短