zoukankan      html  css  js  c++  java
  • Java时间日期和时间戳相互转换

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class Test{

    public static void main(String[] args) throws Exception{
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(sdf.format(new Date()));
    //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据)
    long timeStamp = System.currentTimeMillis();
    logger.info("timeStamp:"+timeStamp);
    //这个是你要转成后的时间的格式
    SimpleDateFormat sdff=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // 时间戳转换成时间
    String sd = sdff.format(new Date());
    System.out.println("sd:"+sd);//打印出你要的时间
    dateToStamp(sd);
    System.out.println("dateToStamp(sd):"+dateToStamp(sd));

    long time = 30*60*1000;//30分钟
    Date beforeDate = new Date((new Date()).getTime() - time);//30分钟前的时间
    System.out.println("beforeDate:"+beforeDate);
      //时间格式转换
    SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM d HH:mm:ss 'CST' yyyy", Locale.ENGLISH);
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String format1 = sdf2.format(sdf1.parse(beforeDate.toString()));
    System.out.println("format1:"+format1);
    System.out.println("beforeDate:"+dateToStamp(format1));


    }

    //将时间转换为时间戳
    public static String dateToStamp(String s) throws ParseException {
    String res;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = simpleDateFormat.parse(s);
    long ts = date.getTime();
    res = String.valueOf(ts);
    return res;
    }

    //将时间戳转换为时间
    public static String stampToDate(String s){
    String res;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    long lt = new Long(s);
    Date date = new Date(lt);
    res = simpleDateFormat.format(date);
    logger.info("res:"+res);
    return res;
    }
     }
  • 相关阅读:
    [原]three.js 地形法向量生成
    C# 创建XML文档
    <转载>在C#中操作XML(基础操作)
    <转载>Visual C#.NetSocket篇
    <转载>批处理重定向中的秘密
    <转载>最基本的Socket编程C#版
    <转载>在.NET中运行外部程序的3种方法
    <转载>修改Win7远程桌面端口
    <转载>Visual C#.NetTCP篇
    <转载>C#中的委托和事件(续)
  • 原文地址:https://www.cnblogs.com/shenhaha520/p/12619583.html
Copyright © 2011-2022 走看看