时间日期格式转换
Time Limit: 1000 ms
Memory Limit: 65536 KiB
Problem Description
而北美所用的日期格式则为“月月/日日/年年年年”或”mm/dd /yyyy”,如将“2010/11/20”改成这种格式,对应的则是”11/20/2010”。对于时间的格式,则常有12小时制和24小时制
12小时制的表示方法是”05:30:00pm”。注意12:00:00pm表示中午12点,而12:00:00am 表示凌晨12点。
第一行为一个整数T(T<=20),代表总共需要转换的时间日期字符串的数目。
<span 18px;="" \"="">接下来的总共T行,每行都是一个需要转换的时间日期字符串。
Output
分行输出转换之后的结果
Sample Input
2 2010/11/20-12:12:12 1970/01/01-00:01:01
Sample Output
11/20/2010-12:12:12pm 01/01/1970-12:01:01am
Hint
Source
1./*使用Date类和String.format()*/
import java.util.Scanner;
import java.util.regex.*;
import java.util.Date;
import java.util.Locale;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String []argc) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss");
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
int n = in.nextInt();
Date d = null;
String line = in.nextLine();
for(int i = 0; i < n; i++) {
line = in.nextLine();
try {
d = dateFormat.parse(line);
}catch(Exception e){}
finally{
String l = String.format(Locale.US,"%tm/%<td/%<tY-%<tI:%<tM:%<tS%<tp", d);
System.out.println(l);
}
}
}
in.close();
}
}
2.使用正则表达式
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String []argc) {
Scanner in = new Scanner(System.in);
int n;
String str = "[\\d]+";
Pattern regex = Pattern.compile(str);
while(in.hasNext()) {
n = in.nextInt();
String line = in.nextLine();
for(int i = 0; i < n; i++) {
line = in.nextLine();
Matcher m = regex.matcher(line);
ArrayList<Integer> al = new ArrayList<Integer>();
while(m.find()) {
al.add(Integer.valueOf(m.group()));
}
int M;
if(al.get(3) == 0) {
M = 12;
}
else if(al.get(3) == 24){
M = 12;
al.set(2, al.get(2) + 1);
}
else if(al.get(3) > 12){
M = al.get(3) % 12;
}
else {
M = al.get(3);
}
System.out.printf("%02d/%02d/%04d-", al.get(1), al.get(2), al.get(0));
System.out.printf("%02d:%02d:%02d", M , al.get(4), al.get(5));
if(al.get(3) >= 12) {
System.out.println("pm");
}
else {
System.out.println("am");
}
}
}
in.close();
}
}