日期格式化的Java函数
在Java中,日期格式化成字符串是一项很常见的任务,尤其是在与数据库或其他系统进行交互时。Java提供了许多相关的类和函数来进行日期的格式化。
1. SimpleDateFormat类
SimpleDateFormat是Java中一个十分重要的日期格式化类,可以让我们十分容易地将日期格式化为字符串,或将字符串转换为日期。下面是一个使用SimpleDateFormat类进行日期格式化的示例代码:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(now);
System.out.println(formattedDate);
}
}
输出结果为:2021-10-05 17:11:49
上述代码中,我们首先创建了一个Date对象,表示当前时间。然后,我们使用SimpleDateFormat类创建了一个格式化器sdf,并将其格式化模板设为“yyyy-MM-dd HH:mm:ss”,表示输出的日期格式为年-月-日 时:分:秒。最后,我们使用sdf对当前时间进行了格式化,将其存储到一个字符串formattedDate中,并将其输出。
2. DateTimeFormatter类
Java 8引入了一个新的日期时间API,包含了许多用于处理日期和时间的类和方法。其中,DateTimeFormatter类是一个类似于SimpleDateFormat的日期格式化类,用于将日期和时间对象格式化为字符串,或将字符串解析返回为日期和时间对象。
下面是一个使用DateTimeFormatter类进行日期格式化的示例代码:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatterExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = now.format(formatter);
System.out.println(formattedDateTime);
}
}
输出结果为:2021-10-05 17:11:49
与SimpleDateFormat类的使用方式类似,我们首先创建了一个LocalDateTime对象表示当前时间。然后,我们使用DateTimeFormatter类创建了一个格式化器formatter,并将其格式化模板设为“yyyy-MM-dd HH:mm:ss”,表示输出的日期格式为年-月-日 时:分:秒。最后,我们使用formatter对当前时间进行了格式化,并将其存储到一个字符串formattedDateTime中,并将其输出。
3. java.time.format包中的其他类和方法
Java中还有许多其他的日期格式化相关类和方法,比如java.time.format包中的其他类和方法,如DateTimeFormatterBuilder、DateTimeParseException等。
例如,下面是一个使用DateTimeFormatterBuilder类创建自定义格式化器的示例代码:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.ResolverStyle;
public class CustomFormatterExample {
public static void main(String[] args) {
LocalDate now = LocalDate.now();
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendLiteral("Today is ")
.appendValue(LocalDate.DAY_OF_MONTH).appendLiteral("/")
.appendValue(LocalDate.MONTH_OF_YEAR).appendLiteral("/")
.appendValue(LocalDate.YEAR).appendLiteral(".")
.toFormatter().withResolverStyle(ResolverStyle.STRICT);
String formattedDate = now.format(formatter);
System.out.println(formattedDate);
}
}
输出结果为:Today is 5/10/2021.
上述代码中,我们使用DateTimeFormatterBuilder类创建了一个自定义格式化器formatter,它的输出格式为“Today is 日/月/年.”。最后,我们对当前日期进行格式化,并将其输出。
另外,还有一些用于处理日期和时间的工具类,如java.time.LocalDate、java.time.LocalTime、java.time.LocalDateTime等类,它们也提供了一些常用的日期和时间操作方法,如获取当前时间、获取年份、月份、月中第几天、星期几等。与此同时,java.util.Calendar和java.util.Date也是Java中常用的日期和时间类,在处理日期和时间时同样有着重要的作用。
总之,日期格式化是Java中一个重要的任务,在Java中,我们可以使用SimpleDateFormat类、DateTimeFormatter类、DateTimeFormatterBuilder类以及其他的日期时间类和方法来完成这项任务,具有十分灵活和多样化的格式化方式。
