本文目錄一覽:
java時間格式轉換
實現思路就是先通過SimpleDateFormat方法定義一個時間類型的格式,之後SimpleDateFormat的format方法將一個符合時間格式的字符串匹配成對應的格式
舉例:
String str0 = “2015年07月05日”;
Date d1 = new SimpleDateFormat(“yyyy年MM月dd日”).parse(str0);//定義起始日期
SimpleDateFormat sdf0 = new SimpleDateFormat(“yyyy”);//定義一個只有年份的
SimpleDateFormat sdf1 = new SimpleDateFormat(“MM”);//月份的
SimpleDateFormat sdf2= new SimpleDateFormat(“dd”);//日的
String str1 = sdf0.format(d1);//取出特定日期d1的年份
String str2 = sdf1.format(d1);//取出特定日期d1的月份
String str3 = sdf2.format(d1);//取出特定日期d1的日
System.out.println(“年份為:”+str1);
System.out.println(“月份為:”+str2);
System.out.println(“日為:”+str3);
java 時間格式的轉換
public class myMain {
public static void main(String[] args) {
// 日曆類
Calendar calendar = Calendar.getInstance();// 實例化
int year = calendar.get(Calendar.YEAR);// 年
int mouth = calendar.get(Calendar.MONTH) + 1;// 月
int day = calendar.get(Calendar.DAY_OF_MONTH);// 幾號
int hour = calendar.get(Calendar.HOUR);// 小時
int minute = calendar.get(Calendar.MINUTE);// 分
int second = calendar.get(Calendar.SECOND);// 秒
// 設置制定年月日
calendar.set(2014, 11, 1, 1, 1, 1);
year = calendar.get(Calendar.YEAR);// 年
mouth = calendar.get(Calendar.MONTH);// 月
day = calendar.get(Calendar.DAY_OF_MONTH);// 幾號
hour = calendar.get(Calendar.HOUR);// 小時
minute = calendar.get(Calendar.MINUTE);// 分
second = calendar.get(Calendar.SECOND);// 秒
System.out.println(year + “=” + mouth + “=” + day + “=” + hour + “=”
+ minute + “=” + second);
// 獲取指定格式輸出日期
Date date = new Date();// 可以使用時間錯
SimpleDateFormat dateFormat = new SimpleDateFormat(
“yyyy-MM-dd HH:mm:ss”);
String riqi = dateFormat.format(date);
System.out.println(riqi);
// 獲得2010年9月13日22點36分01秒 的Date對象
SimpleDateFormat dateFormat2 = new SimpleDateFormat(
“yyyy-MM-dd HH:mm:ss”);
Date myDate2 = null;
try {
myDate2 = dateFormat2.parse(“2010-09-13 22:36:01”);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long myie = myDate2.getTime();
long myief=1284388561000L;//後面必須有個L
String rename=dateFormat2.format(new Date(myief));
在java中如何將12小時制的時間轉換為24小時制
Java中將12小時制的時間轉換為24小時制的方式如下:
import java.text.SimpleDateFormat;
import java.util.Date;
public class ceshi {
public static void main(String[] args) {
SimpleDateFormat objSDateFormat = new SimpleDateFormat(
“yyyy-MM-dd HH:mm:ss”);//轉換為24小時制
String strCurrentTime = objSDateFormat.format(new Date());
System.out.println(strCurrentTime);
}
}
註:大寫的HH為24小時制,小寫的hh為12小時制,當然還可以在ss的後面加上 a,這樣可以在後面顯示上下文:顯示效果為“2008-03-24 17:00:14 下午”
運行結果為:
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/184007.html