1. 题目描述
世界上不同国家有不同的写日期的习惯。比如美国人习惯写成“月-日-年”,而中国人习惯写成“年-月-日”。下面请你写个程序,自动把读入的美国格式的日期改写成中国习惯的日期。
输入格式:
输入在一行中按照“mm-dd-yyyy”的格式给出月、日、年。题目保证给出的日期是1900年元旦至今合法的日期。
输出格式:
在一行中按照“yyyy-mm-dd”的格式给出年、月、日。
输入样例:
03-15-2017
输出样例:
2017-03-15
2. 分析
这道题目还是比较简单的
方法一
把输入当成字符串, 然后以"-"分割月日年, 最后输出重新拼接成"年-月-日"的形式
这种方法用时比较久
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] time = sc.nextLine().split("-");
String s = time[2] + "-" + time[0] + "-" + time[1];
System.out.println(s);
}
}
方法二
使用字符串切割的形式, 将输入的"月-日-年"形式切割成"月-日"和"年",然后再拼接
这种方式更快
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String time = sc.nextLine();
String year = time.substring(6);
String md = time.substring(0, 5);
System.out.println(year + "-" + md);
}
}
还可以更简洁一点, 把+
运算符用concat()
代替, 也能变快一点
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String time = sc.nextLine();
String res = time.substring(6).concat("-").concat(time.substring(0, 5));
System.out.println(res);
}
}
方法三
使用Date类和SimpleDateFormat类, 首先我们将输入的字符串转化成Date类型, 然后再从Date类转换成String, 即我们要的格式
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class 日期格式化 {
public static void main(String[] args) throws ParseException {
Scanner sc = new Scanner(System.in);
String time = sc.nextLine();
//先将字符串转换成Date类
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Date date = sdf.parse(time);
//然后将Date类转换成字符串
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
String res = sdf2.format(date);
System.out.println(res);
}
}