一、介紹
Calendar:日曆
GregorianCalendar:陽曆日曆
SimpleDateFormat:簡單日期格式
二、程式語法:
package com.example.date_time;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//取得日期時間
//利用Calendar獲取
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);//年
int month = c.get(Calendar.MONTH);//月
int date= c.get(Calendar.DATE);//日
int day = c.get(Calendar.DAY_OF_MONTH);//日
int hour = c.get(Calendar.HOUR_OF_DAY);//小時 , 24小時計算
int hour2 = c.get(Calendar.HOUR);//小時 ,12小時計算
int minute = c.get(Calendar.MINUTE);//分鐘
int second = c.get(Calendar.SECOND);//秒
Log.i("hour=====>",String.valueOf(hour));
Log.i("hour2=====>",String.valueOf(hour2));
//日期轉換成樣式
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
SimpleDateFormat sdf2 = new SimpleDateFormat("HHmmss");
try {
//日期轉字串
Date d = c.getTime();
String dateString = sdf.format(d);
Log.i("dateString=====>",dateString);
//字串轉日期
String dateString2 = "";
Date dateParse = sdf.parse(dateString);
//日期加一小時} catch (ParseException e) {
Date d1 = c.getTime();
c.add(Calendar.HOUR,1);
String dateString_sum = sdf.format(c.getTime());
Log.i("目前時間==>",sdf.format(d1)+"加一小時後===>"+dateString_sum);
e.printStackTrace();
}
//Time獲取
Time t=new Time(10);
long gettime = t.getTime(); // 取得系統時間。
Log.i("gettime=====>",String.valueOf(gettime));
//=======================比大小
Calendar c_1 = Calendar.getInstance();
Calendar c_2 = Calendar.getInstance();
SimpleDateFormat sdf_1 = new SimpleDateFormat("yyyyMMddHHmmss");
try {
c_1.setTime(sdf_1.parse("20200917025920"));
Date x0 =c_1.getTime();
Date x1 = c_2.getTime();
Log.i("結果",x1.compareTo(x0)+"");// I/結果 :: 1
} catch (ParseException e) {
e.printStackTrace();
}
//日期比大小===========================
Calendar cal1 = new GregorianCalendar(2019, 8, 10);
Calendar cal2 = new GregorianCalendar(2007, 2, 02);
int i = cal1.compareTo(cal2);
System.out.println("結果 :"+i);//結果:1
int j = cal2.compareTo(cal1);
System.out.println("結果 :" + j);//結果:-1
}
}
沒有留言:
張貼留言
影片的問題請留在影片的留言區裡。
部落格不會另外通知給我,所以很難發現你有留言。