2022年5月20日 星期五

Java Date API

0

Java Date API
Java date to string(日期轉字串)

#import java.text.SimpleDateFormat;
#import java.util.Date;
#java.util.Calendar;



//目前時間

Date date = new Date();

//設定日期格式

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//進行轉換

String dateString = sdf.format(date);

System.out.println(dateString);

           
Java string to date(字串轉日期)
#

//欲轉換的日期字串

String dateString = "2010-03-02 20:25:58";

//設定日期格式

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//進行轉換

Date date = sdf.parse(dateString);

System.out.println(date);

Add Date
#


String dt = "2008-01-01";  // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1);  // number of days to add
dt = sdf.format(c.getTime());  // dt is now the new date

Difference in days between two dates in Java?
#

    Calendar calendar1 = Calendar.getInstance();
    Calendar calendar2 = Calendar.getInstance();


    calendar1.set();
    calendar2.set();
    long milliseconds1 = calendar1.getTimeInMillis();
    long milliseconds2 = calendar2.getTimeInMillis();
    long diff = milliseconds2 - milliseconds1;
    long diffSeconds = diff / 1000;
    long diffMinutes = diff / (60 * 1000);
    long diffHours = diff / (60 * 60 * 1000);
    long diffDays = diff / (24 * 60 * 60 * 1000);

    System.out.println("\nThe Date Different Example");
    System.out.println("Time in milliseconds: " + diff + " milliseconds.");
    System.out.println("Time in seconds: " + diffSeconds + " seconds.");
    System.out.println("Time in minutes: " + diffMinutes + " minutes.");
    System.out.println("Time in hours: " + diffHours + " hours.");
    System.out.println("Time in days: " + diffDays + " days.");




check if date() is monday?
#



Calendar cal = Calendar.getInstance();
cal.setTime(theDate);
boolean monday = cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY;

Java Get Hours / Minutes
#
Date date = new Date();   // given date
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date);   // assigns calendar to given date 
calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
calendar.get(Calendar.HOUR);        // gets hour in 12h format
calendar.get(Calendar.MONTH);       // gets month number, NOTE this is zero based!

0 意見:

張貼留言