62,614
社区成员
发帖
与我相关
我的任务
分享
try{
按"yyyy.MM.dd"转换;
返回转换好的Date;
}catch (Exception e){
//doNothing;
}
try{
按"yyyy.MM"转换;
返回转换好的Date;
}catch(Exception e){
//doNothing;
}
......
走到最后则说明是无法识别的格式,返回空串;(或者抛出异常==)
/****
* 日期String串转Date
* @param str
* @return
*/
public static Date parseDate(String str){
Date d = new Date();
String oper = str;
if(oper.indexOf('.')!=-1){
int count = 0;
while(oper.indexOf('.')!=-1){
count++;
oper = oper.substring(oper.indexOf('.')+1);
}
if(count ==1){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");
try {
d = sdf.parse(str);
System.out.println(sdf.format(d));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(count==2){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
try {
d = sdf.parse(str);
System.out.println(sdf.format(d));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if(str.indexOf('-')!=-1){
int count = 0;
while(oper.indexOf('-')!=-1){
count++;
oper = oper.substring(oper.indexOf('-')+1);
}
if(count ==1){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
try {
d = sdf.parse(str);
System.out.println(sdf.format(d));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(count==2){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
d = sdf.parse(str);
System.out.println(sdf.format(d));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return d;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "1990.8.8";
//String str2 = "1990-9-4";
parseDate(str);
}
/****
* 日期String串转Date
* @param str
* @return
*/
public static Date parseDate(String str){
Date d = new Date();
if(str.indexOf('.')!=-1){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
try {
d = sdf.parse(str);
System.out.println(sdf.format(d));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(str.indexOf('-')!=-1){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
d = sdf.parse(str);
System.out.println(sdf.format(d));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return d;
}