如何使用Java从Date中提取日期,月份和年份? [英] How to extract day, month and year from Date using Java?

查看:122
本文介绍了如何使用Java从Date中提取日期,月份和年份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date date = formatter.parse("2020/05/06"); 

我需要从中提取日期,月份和年份

I need to extract day, month and year from it i.e.

int day = 06;
int  month = 05;
int year = 2020;

但是当我使用

int day = date.getDay();
int month = date.getMonth();
int day = date.getYear(); 

它不起作用.

推荐答案

不要使用 Date ,因为它已过时.使用 LocalDate DateTimeFormatter 如下.

Don't use Date as it is deprecated. Use LocalDate and DateTimeFormatter as follows.

LocalDate ld  = LocalDate.parse("2020/05/06", 
              DateTimeFormatter.ofPattern("yyyy/MM/dd"));
int year = ld.getYear();
int month = ld.getMonthValue();
int day = ld.getDayOfMonth();
System.out.println(month + " " + day + " " + year);

打印

5 6 2020

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆