Java时间转换只取两位年份
引言
在Java开发中,经常需要对时间进行转换和格式化。有时候,我们只关心年份的后两位,而不需要具体的月份和日期。本文将教你如何使用Java代码实现时间转换,只取两位年份。
流程图
journey
title 时间转换流程
section 转换时间
描述 用户输入原始时间
描述 调用时间转换函数
描述 输出转换后的时间
甘特图
gantt
dateFormat YYYY-MM-DD
title 时间转换甘特图
section 任务一
转换时间 :done, 2021-10-01, 1d
section 任务二
编写测试用例 :active, 2021-10-02, 1d
运行测试用例 :2021-10-03, 1d
修复bug :2021-10-04, 1d
步骤
- 首先,我们需要获取用户输入的原始时间,然后将其转换为Java的
Date
对象。可以使用SimpleDateFormat
类来实现。
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeConverter {
public static Date convertStringToDate(String timeString) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
return format.parse(timeString);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
在上面的代码中,我们定义了一个convertStringToDate
方法,它接收一个字符串类型的时间作为参数,返回一个Date
对象。我们使用SimpleDateFormat
类来定义时间的格式,这里使用的格式是"yyyy-MM-dd",你可以根据自己的需求进行修改。
- 接下来,我们需要将获取到的
Date
对象转换为只包含两位年份的字符串。可以使用SimpleDateFormat
类的format
方法来实现。
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeConverter {
public static Date convertStringToDate(String timeString) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
return format.parse(timeString);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String convertDateToTwoDigitYearString(Date date) {
SimpleDateFormat format = new SimpleDateFormat("yy");
return format.format(date);
}
}
在上面的代码中,我们定义了一个convertDateToTwoDigitYearString
方法,它接收一个Date
对象作为参数,返回一个只包含两位年份的字符串。我们同样使用SimpleDateFormat
类来定义时间的格式,这里使用的格式是"yy",表示只取年份的后两位。
- 最后,我们可以测试一下我们的代码是否正确。可以编写一个测试类来验证。
public class TestTimeConverter {
public static void main(String[] args) {
String timeString = "2021-10-01";
Date date = TimeConverter.convertStringToDate(timeString);
String twoDigitYearString = TimeConverter.convertDateToTwoDigitYearString(date);
System.out.println(twoDigitYearString);
}
}
运行上面的测试类,输出结果为"21",表示我们成功地将"2021-10-01"转换为了只包含两位年份的字符串。
总结
本文介绍了如何使用Java代码实现时间转换,只取两位年份。通过使用SimpleDateFormat
类,我们可以方便地定义时间的格式,并进行转换。希望本文对你有所帮助,如果有任何问题,欢迎留言讨论。