欢迎访问宙启技术站
智能推送

Java函数示例:如何格式化输出时间和日期

发布时间:2023-06-19 04:32:09

在Java语言中,与时间和日期有关的操作经常被使用。而在输出时间和日期时,我们往往需要进行一定的格式化。Java中提供了大量的函数可以帮助我们完成这个任务。下面我们来看一些Java函数的示例,以格式化输出时间和日期。

1. SimpleDateFormat类

SimpleDateFormat类是Java中一个常见的日期格式化工具类,可以将日期和时间格式化成指定的格式。使用时,我们需要创建一个SimpleDateFormat类对象,并通过构造函数传入一个日期格式的字符串,然后使用format()方法进行格式化输出。

示例代码:

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

public class FormatTimeDemo{
    public static void main(String[] args){
        Date date = new Date();
        DateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        System.out.println(sdf.format(date));
    }
}

输出结果为:

2021年05月23日 16时08分52秒

2. DateTimeFormatter类

DateTimeFormatter类是Java 8中提供的一种日期和时间格式化工具类,可以将日期和时间格式化成指定的格式。使用时,我们需要通过ofPattern()方法创建一个DateTimeFormatter类对象,并通过format()方法进行格式化输出。

示例代码:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class FormatDateTimeDemo{
    public static void main(String[] args){
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
        System.out.println(now.format(formatter));
    }
}

输出结果为:

2021年05月23日 16时08分52秒

3. Calendar类

Calendar类是Java中表示日期和时间的一种方式,可以对日期和时间进行格式化输出。使用时,我们需要创建一个Calendar类对象,并设置需要格式化的日期和时间字段,然后使用get()方法获取指定的字段值。

示例代码:

import java.util.Calendar;

public class FormatCalendarDemo{
    public static void main(String[] args){
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        System.out.printf("%04d年%02d月%02d日 %02d时%02d分%02d秒%n", year, month, day, hour, minute, second);
    }
}

输出结果为:

2021年05月23日 16时08分52秒

综上所述,Java提供了多种函数可以帮助我们格式化输出时间和日期。开发者在实际开发中可以根据具体情况选用合适的方式。