基于Java的时间转换:Date、Timestamp和String时间转化

本文介绍了一种在Java中进行日期时间转换的方法,包括从String类型转换为Date类型、从Date类型转换为String类型以及Timestamp与String类型的相互转换。通过具体的代码实例展示了如何使用SimpleDateFormat类完成这些转换。
package ZIPUtil;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

//---------String 转换 Date类型-------------------
String date1 = "2017-12-01 12:01:56"; //设定字符串时间
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//根据字符串的时间格式设定时间模板,yyyy代表“年”,MM 代表"月", dd代表“天”, HH 代表小时,mm代表分钟,ss 代表秒,SSS代表毫秒 
Date d1 = new Date(); 
try {
d1 = df1.parse(date1);//解析字符串时间
System.out.println("d1:"+d1); //输出到控制台:Fri Dec 01 12:01:56 CST 2017
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


//--------- Date转换 String类型-------------------
Date d2 = new Date(); //创建一个新的时间对象,目的获取当前的时间
DateFormat df2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//根据字符串的时间格式设定时间模板,yyyy代表“年”,MM 代表"月", dd代表“天”, HH 代表小时,mm代表分钟,ss 代表秒,SSS代表毫秒
String date2 = df2.format(d2);//将时间对象输出字符串时间
System.out.println("date2:"+date2);//字符串时间:



//------------Timestamp 和 String类型胡转-------------------
Timestamp ts = new Timestamp(System.currentTimeMillis()); 
DateFormat df3 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");//根据字符串的时间格式设定时间模板,yyyy代表“年”,MM 代表"月", dd代表“天”, HH 代表小时,mm代表分钟,ss 代表秒,SSS代表毫秒

//Timestamp使用toString转化成字符串
System.out.println("toString:"+ts.toString());
//使用DateFormat转化成String
System.out.println("df3:"+df3.format(ts));


}


}

  

转载于:https://www.cnblogs.com/lihaiming93/p/8116507.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值