Java basics (date acquisition and conversion)

1. Date acquisition

Date date=new Date();
DateFormat dt=DateFormat.getDateTimeInstance();
//将时间打印成本地格式
System.out.println(dt.format(date));
//简便的写法
String datetime=DateFormat.getDateTimeInstance().format(date);
System.out.println(datetime);

operation result:

2. Date formatting

DateFormat df=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date=new Date();
String s=df.format(date);
System.out.println(s);

operation result:

note:

The upper yyyy-MM-dd specified format, specify the format specific rules we described with reference SimpleDateFormat class, which is the rule in a string, the following letters will replace part of the corresponding time, the remaining content is output :

  • When it appearsy时,会将y替换成年
  • When it appearsM时,会将M替换成月
  • When it appearsd时,会将d替换成日
  • When it appearsH时,会将H替换成时
  • When it appearsm时,会将m替换成分
  • When it appearss时,会将s替换成秒

3.日期的转换

 String s="2019年6月24日 11:13:12";
 DateFormat df=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
 Date date=df.parse(s);
 System.out.println(date.toLocaleString());

Description: Parse the string to generate a date.

  1. format method, used to convert Date objects to String
  2. The parse method is used to convert the String to Date (when converting, the String must conform to the specified format , otherwise it cannot be converted).
  3. The format and parse methods will throw an exception, just throw the exception in the main method

        public static void main(String[] args) throws ParseException

4. Case

How many days have you been born

Code example:

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

public class demo2 {
    public static void main(String[] args) throws ParseException {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入你的出生日期:格式(1998-1-1)");
        String s=sc.next();
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        //把字符串转换为日期
        Date date=df.parse(s);
        //算出生的毫秒数
        long time=date.getTime();
        //当前时间的毫秒数
        long currenttime=System.currentTimeMillis();
        long days=(currenttime-time)/(60*60*24*1000);
        System.out.println("您出生已经"+days+"了");
    }
}

operation result:

Published 75 original articles · praised 164 · 110,000 views

Guess you like

Origin blog.csdn.net/qq_41679818/article/details/93746400