如何在Java 8中将Date转换为String?
Java的java.time包提供日期,时间,实例和持续时间的API。它提供了各种类,例如Clock,LocalDate,LocalDateTime,LocalTime,MonthDay,Year,YearMonth等。与以前的替代方法相比,使用此软件包的类,您可以通过简单得多的方式获取与日期和时间相关的详细信息。
Java.time.LocalDate-此类表示ISO-8601日历系统中不带时区的日期对象。now()此类的方法从系统时钟获取当前日期。
toString()LocalDate类的方法将当前Date对象的日期值转换为String并返回它。
示例
以下Java示例接受用户的月,年和日值,从中创建日期对象,然后将其转换为String。
import java.time.LocalDate;
import java.util.Scanner;
public class DateToString {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the year: ");
int year = sc.nextInt();
System.out.println("Enter the month: ");
int month = sc.nextInt();
System.out.println("Enter the day: ");
int day = sc.nextInt();
//获取给定的日期值
LocalDate givenDate = LocalDate.of(year, month, day);
//将给定日期转换为String-
String date = givenDate.toString();
System.out.println("给定日期:"+date);
}
}输出结果
Enter the year: 2019 Enter the month: 09 Enter the day: 26 给定日期:2019-09-26
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短