http://www.linuxidc.com/Linux/2010-04/25584.htm
http://www.linuxidc.com/Linux/2010-04/25584p2.htm
Java中日期格式转换
/**
* 字符串转
* yy/MM/dd HH:mm:ss pm 如 '2002/1/1 17:55:00 pm'
* yy-MM-dd HH:mm:ss 如 '2002-1-1 17:55:00'
* yy-MM-dd HH:mm:ss am 如 '2002-1-1 17:55:00 am'
* @param time String 字符串
* @return Date 日期
*/
public static Date stringToDate(String time){
SimpleDateFormat formatter;
int tempPos=time.indexOf("AD") ;
time=time.trim() ;
formatter = new SimpleDateFormat ("yyyy.MM.dd G 'at' hh:mm:ss z");
if(tempPos>-1){
time=time.substring(0,tempPos)+
"公元"+time.substring(tempPos+"AD".length());//china
formatter = new SimpleDateFormat ("yyyy.MM.dd G 'at' hh:mm:ss z");
}
tempPos=time.indexOf("-");
if(tempPos>-1&&(time.indexOf(" ")-1) &&(time.indexOf(" ")>-1)){
formatter = new SimpleDateFormat ("yyyy/MM/dd HH:mm:ss");
}
else if((time.indexOf("-")>-1) &&(time.indexOf(" ")>-1)){
formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
}
else if((time.indexOf("/")>-1) &&(time.indexOf("am")>-1) ||(time.indexOf("pm")>-1)){
formatter = new SimpleDateFormat ("yyyy-MM-dd KK:mm:ss a");
}
else if((time.indexOf("-")>-1) &&(time.indexOf("am")>-1) ||(time.indexOf("pm")>-1)){
formatter = new SimpleDateFormat ("yyyy-MM-dd KK:mm:ss a");
}
ParsePosition pos = new ParsePosition(0);
java.util.Date ctime = formatter.parse(time, pos);
return ctime;
}
/**
* 将java.util.Date 格式转换为字符串格式'yyyy-MM-dd HH:mm:ss'(24小时制)
* 如Sat May 11 17:24:21 CST 2002 to '2002-05-11 17:24:21'
* @param time Date 日期
* @return String 字符串
*/
public static String dateToString(Date time){
SimpleDateFormat formatter;
formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
String ctime = formatter.format(time);
return ctime;
}
/**
* 将java.util.Date 格式转换为字符串格式'yyyy-MM-dd HH:mm:ss a'(12小时制)
* 如Sat May 11 17:23:22 CST 2002 to '2002-05-11 05:23:22 下午'
* @param time Date 日期
* @param x int 任意整数如:1
* @return String 字符串
*/
public static String dateToString(Date time,int x){
SimpleDateFormat formatter;
formatter = new SimpleDateFormat ("yyyy-MM-dd KK:mm:ss a");
String ctime = formatter.format(time);
return ctime;
}
/**
*取系统当前
字串日期格式转换
用的API是SimpleDateFormat,它是属於java.text.SimpleDateFormat,所以请记得import进来!
用法:
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
这一行最重要,它确立了转换的格式,yyyy是完整的西元年,MM是月份,dd是日期, 至於HH:mm:ss就不需要我再解释了吧!
ps:为什麽有的格式大写,有的格式小写,那是怕避免混淆,例如MM是月份,mm是分;HH是24小时制,而hh是12小时制
1.字串转日期:
2002-10-8 15:30:22要把它转成日期,
分享到:
2010-10-27 14:37
浏览 1650
评论