您的位置:首页 > 其它

SimpleDateFormate日期字符串转换(墨雪亲测)

2016-12-05 10:06 288 查看
1.字符串日期转换为date型:

//SimpleDateFormat中的parse方法可以
//把String型的字符串转换成特定格式的date类型

public static void main(String[] args) {
String dStr = "2001.12.12-08:23:21";
Date d = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd-HH:mm:ss");
try {
d = sdf.parse(dStr);
} catch (ParseException pe) {
System.out.println(pe.getMessage());
}
System.out.println(d);
System.out.println(d.getTime());
}


2.date/calendar类型转换为指定格式日期:

public class FormatDateTime {

public static void main(String[] args) {
SimpleDateFormat myFmt=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
SimpleDateFormat myFmt1=new SimpleDateFormat("yy/MM/dd HH:mm");
SimpleDateFormat myFmt2=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//等价于now.toLocaleString()
SimpleDateFormat myFmt3=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E ");
SimpleDateFormat myFmt4=new SimpleDateFormat(
"一年中的第 D 天 一年中第w个星期 一月中第W个星期 在一天中k时 z时区");
Date now=new Date();
System.out.println(myFmt.format(now));
System.out.println(myFmt1.format(now));
System.out.println(myFmt2.format(now));
System.out.println(myFmt3.format(now));
System.out.println(myFmt4.format(now));
System.out.println(now.toGMTString());
System.out.println(now.toLocaleString());
System.out.println(now.toString());
}

}


效果:

2004年12月16日 17时24分27秒

04/12/16 17:24

2004-12-16 17:24:27

2004年12月16日 17时24分27秒 星期四

一年中的第 351 天 一年中第51个星期 一月中第3个星期 在一天中17时 CST时区

16 Dec 2004 09:24:27 GMT

2004-12-16 17:24:27

Thu Dec 16 17:24:27 CST 2004

3.long型的时间与字符串时间的转换:

public class TimeFormat {
//输入参数:2016年12月5日10时55分23秒 周一,得到字符串:1480906523000
public String timeStr_TO_longStr(String time_str) {
String dStr = time_str;
String long_str;
Date d = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒 E");
try {
d = sdf.parse(dStr);
} catch (ParseException pe) {
System.out.println(pe.getMessage());
}
Calendar c=Calendar.getInstance();
c.setTime(d);
long_str=c.getTimeInMillis()+"";
return long_str;
}
//输入参数:1480906523000,得到字符串:2016年12月5日10时55分23秒 周一
public String longStr_TO_timeStr(String long_str){
String longStr = long_str;
long l_value=Long.parseLong(longStr);
Calendar c=Calendar.getInstance();
c.setTimeInMillis(l_value);
String timeStr;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒 E");
timeStr = sdf.format(c.getTime());

return timeStr;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  SimpleDate 日期格式