29 time and date class - cnblog

Keywords: Java Algorithm data structure

1. Time and date

1.1 Date class (application)

  • Overview of Date class

    Date represents a specific time, accurate to milliseconds

  • Date class constructor

Method nameexplain
public Date()Allocate a Date object and initialize it so that it represents the time it is allocated, accurate to milliseconds
public Date(long date)Allocates a Date object and initializes it to represent the specified number of milliseconds from the standard base time
public class DateDemo01 {
    public static void main(String[] args) {
        //public Date(): allocate a Date object and initialize it so that it represents the time it is allocated, accurate to milliseconds
        Date d1 = new Date();
        System.out.println(d1);
        //public Date(long date): assign a Date object and initialize it to indicate that it starts from the standard base time
        Specified number of milliseconds
            long date = 1000*60*60;
        Date d2 = new Date(date);
        System.out.println(d2);
    }
}

1.2 common methods of date class (application)

  • common method
Method nameexplain
public long getTime()Gets the millisecond value of the date object from 00:00:00, January 1, 1970 to the present
public void setTime(long time)Set the time and give the value of milliseconds
import java.util.Date;
/*
    public Date(): Allocate a Date object and initialize it so that it represents the time it is allocated, accurate to milliseconds
    public Date(long date): Allocates a Date object and initializes it to represent the specified number of milliseconds from the standard base time
 */

/*
    public long getTime():Gets the millisecond value of the date object from 00:00:00, January 1, 1970 to the present
    public void setTime(long time):Set the time and give the value of milliseconds
 */

public class test {
    public static void main(String[] args) {
        //Create date object
        Date d = new Date();

        //public long getTime(): gets the millisecond value of the date object from 00:00:00 on January 1, 1970 to the present
        System.out.println(d.getTime()*1.0/1000/60/60/24/365+"year");

        //public void setTime(long time): sets the time. The value given is milliseconds
//        long time = 1000*60*60;
        long time = System.currentTimeMillis();
        d.setTime(time);

        System.out.println(d);
    }
}

1.3 SimpleDateFormat class (application)

  • SimpleDateFormat class overview

    SimpleDateFormat is a concrete class for formatting and parsing dates in a locale sensitive manner.
    We focus on date formatting and parsing

  • SimpleDateFormat class constructor

Method nameexplain
public SimpleDateFormat()Construct a SimpleDateFormat, using the default mode and date format
public SimpleDateFormat(String pattern)Construct a SimpleDateFormat using the given pattern and the default date format
  • Common methods of the SimpleDateFormat class

    • Format (from Date to String)

      • public final String format(Date date): formats the date into a date / time string
    • Parsing (from String to Date)

      • public Date parse(String source): parses text from the beginning of a given string to generate a date
        Sample code
package Heima.SimpleDateFormat.test1;

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

/*
    Construction method:
        public SimpleDateFormat​():Construct a SimpleDateFormat, using the default mode and date format
        public SimpleDateFormat​(String pattern):Construct a SimpleDateFormat using the given pattern and the default date format

    Format: from Date to String
        public final String format(Date date): Format the date as a date / time string

    Parsing: from String to Date
        public Date parse​(String source): Parses text from the beginning of a given string to generate a date
 */
public class SimpleDateFormatDemo {
    public static void main(String[] args) throws ParseException {
        //Format: from Date to String
        Date d = new Date();
//        SimpleDateFormat sdf = new SimpleDateFormat();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");

        String s = sdf.format(d);

        System.out.println(s);

        //Parse String---Date
        String ss = "2029-08-22 11:11:11";//ParseException
        SimpleDateFormat sdf2 =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final Date dd = sdf2.parse(ss);
        System.out.println(dd);
    }
}

Case: Date tool class

  • Case requirements
    Define a date tool class (DateUtils), which contains two methods: convert the date to a string in the specified format; Parses a string into a specified format
    Then define a test class (DateDemo) to test the methods of the date tool class

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

public class DateUtils {
    //Object private ownership
    private DateUtils(){}

    /*
    Converts the date to a string in the specified format
    Return value type: String
    Parameters: date, date, string format
    */
    public static String  datetostring(Date d, String format){
        SimpleDateFormat sdf =new SimpleDateFormat(format);
        String d1 = sdf.format(d);
        return d1;
    }
    /*
    Parses the string to a date in the specified format
    Return value type: Date
    Parameters: String s, String format
    */
    public static Date stringtodate(String s,String format) throws ParseException {
        SimpleDateFormat dd = new SimpleDateFormat(format);
        Date p = dd.parse(s);
        return p;
    }
}

import java.text.ParseException;
import java.util.Date;

public class DateUtilsTest {
    public static void main(String[] args) throws ParseException {
        Date d = new Date();
        String format = "yyyy year MM month dd day HH Time mm branch ss second";

        //Date--String
        String datetostring = DateUtils.datetostring(d, format);
        System.out.println(datetostring);

        //String--Date
        String ss = "2029-08-22 11:11:11";
        String format2 = "yyyy-MM-dd HH:mm:ss";
        Date stringtodate = DateUtils.stringtodate(ss, format2);
        System.out.println(stringtodate);


    }
}

1.4Clalendar (calendar)

  • Calendar Class overview
    Calendar provides some methods for the conversion between a specific moment and a set of calendar fields, and some methods for manipulating calendar fields
    Calendar provides a class method, getInstance, to get commonly useful objects of this type.
    This method returns a Calendar object.
    Its calendar field has been initialized with the current date and time: Calendar rightNow = Calendar.getInstance();

  • Common methods of Calendar Class

Method nameexplain
public int get(int field)Returns the value of the given calendar field
public abstract void add(int field, int amount)Add or subtract the specified amount of time from the given calendar field according to the rules of the calendar
public final void set(int year,int month,int date)Set the month, year and day of the current calendar
import java.util.Calendar;

/*
    Calendar It provides some methods for the conversion between a specific moment and a set of calendar fields, and some methods for manipulating calendar fields

    Calendar A class method getInstance is provided to obtain commonly useful objects of this type. This method returns a Calendar object,
    Its calendar field has been initialized with the current date and time: Calendar rightNow = Calendar.getInstance();
 */
public class CalendarDemo {
    public static void main(String[] args) {
        //Get object
        Calendar c = Calendar.getInstance();//Polymorphic common objects
        System.out.println(c);

        //public int get(int filed)
        int year = c.get(Calendar.YEAR);
        int mouths = c.get(Calendar.MONTH)+1;
        int days = c.get(Calendar.DATE);
        System.out.println(year+"Year"+mouths+days);

    }
}

        //Demand 1: today 3 years ago
//        c.add(Calendar.YEAR,-3);
//        year = c.get(Calendar.YEAR);
//        month = c.get(Calendar.MONTH) + 1;
//        date = c.get(Calendar.DATE);
//        System.out.println(year + "year" + month + "month" + date + "day");

        //Demand 2: 10 days after 10 years
//        c.add(Calendar.YEAR,10);
//        c.add(Calendar.DATE,-10);
//        year = c.get(Calendar.YEAR);
//        month = c.get(Calendar.MONTH) + 1;
//        date = c.get(Calendar.DATE);
//        System.out.println(year + "year" + month + "month" + date + "day");

        //public final void set (int year,int month,int date): sets the month, year and day of the current calendar
        c.set(2050,10,10);
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH) + 1;
        date = c.get(Calendar.DATE);
        System.out.println(year + "year" + month + "month" + date + "day");

Case: February day

  • Get the number of days in February of any year

/*
    Requirements:
        Get the number of days in February of any year

    Idea:
        1:Enter any year on the keyboard
        2:Set year, month and day of calendar object
            Year: from keyboard entry
            Month: set to March. The month starts from 0, so the set value is 2
            Day: set to 1 day
        3:3 March 1 is pushed forward one day, which is the last day of February
        4:Just get the output of this day
 */

import java.util.Calendar;
import java.util.Scanner;

public class ErYueTian {
    public static void main(String[] args) {
        //Enter any year on the keyboard
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the year:");
        int year = sc.nextInt();

        //Set year, month and day of calendar object
        Calendar c = Calendar.getInstance();
        c.set(year,2,1);

        //March 1 is pushed forward one day, which is the last day of February
        c.add(Calendar.DATE,-1);

        //Just get the output of this day
        int i = c.get(Calendar.DATE);
        System.out.println(year+"In February"+i+"day");

    }
}

Posted by glueater on Sun, 21 Nov 2021 18:58:57 -0800