Java时间日期和时间戳相互转换

秒速五厘米 2022-04-16 01:59 637阅读 0赞

Java时间日期和时间戳相互转换

  1. import java.text.ParseException;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. public class Test2 {
  5. public static void main(String[] args) {
  6. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  7. System.out.println(sdf.format(new Date()));
  8. //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据)
  9. long timeStamp = System.currentTimeMillis();
  10. //这个是你要转成后的时间的格式
  11. SimpleDateFormat sdff=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  12. // 时间戳转换成时间
  13. String sd = sdff.format(new Date(timeStamp));
  14. System.out.println(sd);//打印出你要的时间
  15. }
  16. /*
  17. * 将时间转换为时间戳
  18. */
  19. public static String dateToStamp(String s) throws ParseException {
  20. String res;
  21. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  22. Date date = simpleDateFormat.parse(s);
  23. long ts = date.getTime();
  24. res = String.valueOf(ts);
  25. return res;
  26. }
  27. /*
  28. * 将时间戳转换为时间
  29. */
  30. public static String stampToDate(String s){
  31. String res;
  32. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  33. long lt = new Long(s);
  34. Date date = new Date(lt);
  35. res = simpleDateFormat.format(date);
  36. return res;
  37. }
  38. }

发表评论

表情:
评论列表 (有 0 条评论,637人围观)

还没有评论,来说两句吧...

相关阅读