可以使用SimpleDateFormat类将字符串时间转换为Date对象,然后使用Calendar类获取年、月、日等时间单位。

示例代码:

String strTime = "2021-08-25";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(strTime);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

int year = calendar.get(Calendar.YEAR); // 获取年份
int month = calendar.get(Calendar.MONTH) + 1; // 获取月份(注意要加1)
int day = calendar.get(Calendar.DAY_OF_MONTH); // 获取日

String strYear = String.format("%02d", year % 100); // 将年份转换为两位数(例如2021年转换为21)
String strMonth = String.format("%02d", month); // 将月份转换为两位数
String strDay = String.format("%02d", day); // 将日转换为两位数

System.out.println(strYear + " " + strMonth + " " + strDay); // 输出结果:21 08 25

在上面的代码中,使用String.format()方法将年、月、日转换为两位数的字符串,例如将2021年转换为21。

如果要获取其他时间单位,可以参考Calendar类的文档,使用类似的方法获取

java 将string时间yyyy-MM-dd格式年月日分隔为每个单位02取2

原文地址: https://www.cveoy.top/t/topic/hhEN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录