java時間格式化知識整理

MySQL Str to Date (字符串轉換爲日期)函數:str_to_date(str, format)

select str_to_date(‘08/09/2008’, ‘%m/%d/%Y’); – 2008-08-09
select str_to_date(‘08/09/08’ , ‘%m/%d/%y’); – 2008-08-09
select str_to_date(‘08.09.2008’, ‘%m.%d.%Y’); – 2008-08-09
select str_to_date(‘08:09:30’, ‘%h:%i:%s’); – 08:09:30
select str_to_date(‘08.09.2008 08:09:30’, ‘%m.%d.%Y %h:%i:%s’); – 2008-08-09 08:09:30

MySQL Date/Time to Str(日期/時間轉換爲字符串)函數:date_format(date,format), time_format(time,format)

獲得當前日期+時間(date + time)函數:now()

java怎麼格式化時間
怎麼打印出昨天的時間

  package com.test.calendar;
  
  import java.util.Calendar;
  
  import org.junit.Before;
  import org.junit.Test;
  
  public class CalendarDemo {
      Calendar calendar = null;


 @Before
 public void test() {
     calendar = Calendar.getInstance();
 }

 // 基本用法,獲取年月日時分秒星期
 @Test
 public void test1() {
     // 獲取年
     int year = calendar.get(Calendar.YEAR);

     // 獲取月,這裏需要需要月份的範圍爲0~11,因此獲取月份的時候需要+1纔是當前月份值
     int month = calendar.get(Calendar.MONTH) + 1;

     // 獲取日
     int day = calendar.get(Calendar.DAY_OF_MONTH);

     // 獲取時
     int hour = calendar.get(Calendar.HOUR);
     // int hour = calendar.get(Calendar.HOUR_OF_DAY); // 24小時表示

     // 獲取分
     int minute = calendar.get(Calendar.MINUTE);

     // 獲取秒
     int second = calendar.get(Calendar.SECOND);

     // 星期,英語國家星期從星期日開始計算
     int weekday = calendar.get(Calendar.DAY_OF_WEEK);

     System.out.println("現在是" + year + "年" + month + "月" + day + "日" + hour
             + "時" + minute + "分" + second + "秒" + "星期" + weekday);
 }

 // 一年後的今天
 @Test
 public void test2() {
     // 同理換成下個月的今天calendar.add(Calendar.MONTH, 1);
     calendar.add(Calendar.YEAR, 1);

     // 獲取年
     int year = calendar.get(Calendar.YEAR);

     // 獲取月
     int month = calendar.get(Calendar.MONTH) + 1;

     // 獲取日
     int day = calendar.get(Calendar.DAY_OF_MONTH);

     System.out.println("一年後的今天:" + year + "年" + month + "月" + day + "日");
 }

 // 獲取任意一個月的最後一天
 @Test
 public void test3() {
     // 假設求6月的最後一天
     int currentMonth = 6;
     // 先求出7月份的第一天,實際中這裏6爲外部傳遞進來的currentMonth變量
     // 1
     calendar.set(calendar.get(Calendar.YEAR), currentMonth, 1);

     calendar.add(Calendar.DATE, -1);

     // 獲取日
     int day = calendar.get(Calendar.DAY_OF_MONTH);

     System.out.println("6月份的最後一天爲" + day + "號");
 }

 // 設置日期
 @Test
 public void test4() {
     calendar.set(Calendar.YEAR, 2000);
     System.out.println("現在是" + calendar.get(Calendar.YEAR) + "年");

     calendar.set(2008, 8, 8);
     // 獲取年
     int year = calendar.get(Calendar.YEAR);

     // 獲取月
     int month = calendar.get(Calendar.MONTH);

     // 獲取日
     int day = calendar.get(Calendar.DAY_OF_MONTH);

     System.out.println("現在是" + year + "年" + month + "月" + day + "日");
 }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章