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 生女孩红包简短祝福语