JAVA 日期处理

来源:互联网 发布:什么叫网络故障诊断 编辑:程序博客网 时间:2024/06/05 14:46
import org.apache.commons.lang.RandomStringUtils;import org.joda.time.DateTime;import java.math.BigDecimal;import java.text.SimpleDateFormat;public class Demo{    SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");    String randomStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());String  a_str= randomStr + RandomStringUtils.randomNumeric(15);timeFormat.format(new DateTime(new Date()).plusSeconds(5).toDate());timeFormat.format(new DateTime(new Date()).plusDays(5).toDate());}


 String -> Date

String dateStr = "2010/05/04 12:34:23";Date date = new Date();//注意format的格式要与日期String的格式相匹配DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");try {date = sdf.parse(dateStr);System.out.println(date.toString());} catch (Exception e) {e.printStackTrace();}

 Date -> String

String dateStr = "";Date date = new Date();//format的格式可以任意DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");DateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH/mm/ss");try {dateStr = sdf.format(date);System.out.println(dateStr);dateStr = sdf2.format(date);System.out.println(dateStr);} catch (Exception e) {e.printStackTrace();}

String ->Timestamp

Timestamp ts = new Timestamp(System.currentTimeMillis());String tsStr = "2011-05-09 11:49:45";try {ts = Timestamp.valueOf(tsStr);System.out.println(ts);} catch (Exception e) {e.printStackTrace();}

Timestamp -> String

Timestamp ts = new Timestamp(System.currentTimeMillis());String tsStr = "";DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");try {//方法一tsStr = sdf.format(ts);System.out.println(tsStr);//方法二tsStr = ts.toString();System.out.println(tsStr);} catch (Exception e) {e.printStackTrace();}


0 0
原创粉丝点击