How to write Java code for converting time formats?

There are two main aspects involved in Java time format conversion: date formatting and date parsing. Here are two example codes.

  1. Formatting the date:
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatExample {
    public static void main(String[] args) {
        // 当前日期
        Date currentDate = new Date();
        
        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        // 格式化日期
        String formattedDate = sdf.format(currentDate);
        
        // 输出格式化后的日期
        System.out.println("Formatted Date: " + formattedDate);
    }
}
  1. Date parsing:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateParseExample {
    public static void main(String[] args) {
        // 定义日期字符串
        String dateString = "2021-01-01 12:00:00";
        
        // 定义日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        try {
            // 解析日期字符串
            Date parsedDate = sdf.parse(dateString);
            
            // 输出解析后的日期
            System.out.println("Parsed Date: " + parsedDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

In the examples above, the SimpleDateFormat class is used to define date formats, formatting dates using the format() method and parsing dates using the parse() method. In actual use, different date formats can be defined according to one’s own needs.

bannerAds