java 日期基本操作

点击量:82

常用类

Date  获取当前时间,比较时间(after,before)
SimpleDateFormat (format,parse)
Calendar  设置日期,添加日期,获取日起部分数据
GregorianCalendar 公历年

参考

date

测试代码

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateTest {
public static void main(String[] args) {
    System.out.println(dateToString());
    System.out.println(dateToString(stringToDate("2018-9-13 23:11:29")));
    CalendarTest();
}

public static String dateToString() {
    Date date = new Date();
    return dateToString(date);
}

public static String dateToString(Date date) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    return sdf.format(date);
}

public static Date stringToDate(String dateStr) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        return sdf.parse(dateStr);
    } catch (ParseException e) {
        System.out.println("error parse date " + dateStr);
    }
    return null;
}

public static void CalendarTest() {

// Calendar c1 = Calendar.getInstance();
Calendar c1 = new GregorianCalendar();
c1.set(2081, 9, 23, 3, 2, 54);
c1.add(Calendar.DATE, 5);
System.out.println(dateToString(c1.getTime()));

    c1.add(Calendar.YEAR, 2);
    System.out.println(dateToString(c1.getTime()));

    int year = c1.get(Calendar.YEAR);
    int month = c1.get(Calendar.MONTH) + 1;
    int date = c1.get(Calendar.DATE);
    int hour = c1.get(Calendar.HOUR);
    int minute = c1.get(Calendar.MINUTE);
    int second = c1.get(Calendar.SECOND);
    int day = c1.get(Calendar.DAY_OF_WEEK);

    System.out.println(((GregorianCalendar) c1).isLeapYear(2020));

    System.out.printf("%d %d %d %d %d %d %d", year, month, date, hour, minute, second, day);
}

}

java 日期基本操作》有3个想法

发表评论

电子邮件地址不会被公开。

3 × 4 =