Java关于日期的自编的类

本文介绍如何使用Java进行时间操作,包括获取当前时间和过去特定时间段的时间点,并演示了如何将长整型时间戳转换为易读的日期格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.输出当前时间(长整型)和两小时间以前的时间(长整型)

import java.text.SimpleDateFormat;
import java.util.Calendar;


public class dateShow {
 public static void main(String[] args)
 { 
  Calendar c= Calendar.getInstance();
  SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  System.out.println(sf.format(c.getTime()));
  System.out.println(c.getTimeInMillis());
    
  long d=c.getTimeInMillis()-2*60*60*1000;
  System.out.println(sf.format(d));
  System.out.println(d);
 }
}

2.当前时间,前一个到前N个时间点

 import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GetBeforeTime {
 public static String getBeforeTime(String date){ 
     DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
     Date d = new Date(0); 
     try { 
         d = f.parse(date); 
     } catch (Exception e) { 
         e.printStackTrace(); 
     } 
     long Time=(d.getTime()); 
     long datet = Time-15*60* 1000; 
     String ss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(datet); 
     return ss; 
 } 
 public static long getBeforeTimeLong(String date){ 
     DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
     Date d = new Date(0); 
     try { 
         d = f.parse(date); 
     } catch (Exception e) { 
         e.printStackTrace(); 
     } 
     long Time=(d.getTime()); 
     long datet = Time-15*60* 1000;     
     return datet; 
 } 
 public static void getBeforeTimeMore(String date){ 
     DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
     Date d = new Date(0); 
     try { 
         d = f.parse(date); 
     } catch (Exception e) { 
         e.printStackTrace(); 
     } 
     long Time=(d.getTime());
    
     for(int i=0;i<10;i++)
     {
      System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Time-i*60*60* 1000)+" "+(Time-i*60*60* 1000));
     }   
 } 
 
 public static void main(String[] args)
 {
  getBeforeTimeMore(" 2011-06-08 16:44:22");
 }
}

 

 

3.长整型转化成具体的时间:

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class LongChangeDate {
 public static void main(String[] args)
 {
  LongChangeDate lc=new LongChangeDate();
  lc.changedate1(1307384531315l);
 }
  public void changedate1(long strdate){
   Calendar aa = Calendar.getInstance();
   aa.setTimeInMillis(strdate);
   SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
   System.out.println("  "+sf.format(aa.getTime()));
 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值