String转Date 转时间戳

48 篇文章 0 订阅
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;




public class Test4 { 
public static void main(String[] args) {
 SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 String test=df.format(new Date("Sep 1,2015 5:34:28 PM"));
 System.out.println(test);
String end= getTime(test,"yyyy-MM-dd HH:mm:ss"); 
System.out.println("end======"+end);   
 

SimpleDateFormat format =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
Long time=new Long(end);
String d=format.format(time);
System.out.println("d======"+d);
try {
Date date = format.parse(d);
System.out.println("date======"+date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



}
/**
* 将字符串转为时间戳
* @param user_time  例如:user_time = "2015-1-3 09:03"; 
* @param format  格式  例如: "yyyy-M-d HH:mm"; 
* @return
*/
public static String getTime(String user_time,String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date d;
if (isNull(user_time)) {
return "";
}
try {
d = sdf.parse(user_time);
long l = d.getTime();
return String.valueOf(l);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
/**
* [Summary] isNull(方法描述:判断传入的文字是否为空)

* @param context
*            上下文对象
* @return 如果为空或等于null则返回true,否则返回false
*/
public static boolean isNull(String context) {
if ("".equals(context) || context == null) {
return true;
} else {
return false;
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将String类型的时间戳换为Date,你可以使用DateFormat或DateTimeFormatter来实现。 方法一:使用DateFormat 你可以使用DateFormat及其子类SimpleDateFormat来进行格式化和解析日期。首先,你需要创建一个SimpleDateFormat对象,并指定你想要的日期格式,比如"yyyy-MM-dd HH:mm:ss"。然后,使用该对象的parse方法将String类型的时间戳换为Date类型。以下是一个示例代码: ``` DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = simpleDateFormat.parse("2018-06-16 10:00:00");``` 其中,"2018-06-16 10:00:00"是你要换的String类型的时间戳。 方法二:使用DateTimeFormatter(JDK8以上) 如果你使用的是JDK8及以上版本,你可以使用DateTimeFormatter来代替SimpleDateFormat。DateTimeFormatter是线程安全的。首先,你需要创建一个DateTimeFormatter对象,并指定你想要的日期格式,比如"yyyy-MM-dd HH:mm:ss"。然后,使用该对象的parse方法将String类型的时间戳换为LocalDate类型。以下是一个示例代码: ``` DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDate date = LocalDate.parse("2018-06-16 10:00:00", formatter); ``` 其中,"2018-06-16 10:00:00"是你要换的String类型的时间戳。 在以上两种方法中,你可以根据你的具体需求选择适合的方法来进行String类型时间戳换。同时,记得根据你所使用的类库的版本来选择合适的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值