最近从MongoDB中读取时间字符串。由于写入字符串时没有处理,该字符串显示的时间格式很不规律,如“2017-04-14 11:05”,“2017年11月14 11:05”,“2017-11-14日11:05”,“20170414”等。
我听说PHP有个函数可以把各种时间格式的字符串转成linux时间戳。不过Java我不知道有没有这样的函数,所以自己按规则写了一个。先转成时间戳,在转回规定格式。
代码很丑,不优雅,以后想起了再琢磨一下写成工具类。现在先记下来方便用。
package Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Vector;
public class Test{
public static void main(String[] args) {
String term = "20170414";
System.out.println(getTime(term));
}
public static String getTime(String givingTime){
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.ENGLISH);
givingTime = givingTime.replaceAll("([^0-9] )|([^0-9])"," ");
givingTime = givingTime.replaceAll("\\s{1,}", " ");
String[] numbers = givingTime.split(" ");
if (numbers.length == 1){
String time = numbers[0];
SimpleDateFormat format;
if (time.length() == 8)
format = new SimpleDateFormat("yyyyMMdd",Locale.ENGLISH);
else if (time.length() == 14)
format = new SimpleDateFormat("yyyyMMddHHmmss",Locale.ENGLISH);
else if (time.length() > 8){
time = time.substring(0, 8);
format = new SimpleDateFormat("yyyyMMdd",Locale.ENGLISH);
}
else{
format = null;
return sdf.format(new Date(0));
}
Date date = null;
try {
date = format.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return sdf.format(date);
}
Vector<Integer> nums = new Vector<Integer>();
for (int i = 0; i < 6; i++)
nums.add(0);
if (numbers.length > 3){
if(Integer.parseInt(numbers[2]) > 31){
String tmp = numbers[2].substring(0, 2);
if (Integer.parseInt(tmp) > 31)
tmp = numbers[2].substring(0, 1);
numbers[3] = numbers[2].substring(tmp.length());
numbers[2] = tmp;
}
}
for (int i = 0; i < numbers.length; i++){
nums.setElementAt(Integer.parseInt(numbers[i]), i);
System.out.println("i = " + i + ": nums = " + nums.get(i));
}
int year = nums.get(0);
int month = nums.get(1);
int day = nums.get(2);
int hour = nums.get(3);
if (hour > 24) hour = 0;
int min = nums.get(4);
if (min > 60) min = 0;
int sec = nums.get(5);
if (sec > 60) sec = 0;
Calendar calendar = Calendar.getInstance();
System.out.println(year+ " " + (month-1)+ " " + day+ " " + hour+ " " + min+ " " + sec);
calendar.set(year, month-1, day, hour, min, sec);
return sdf.format(calendar.getTime());
}
}