比方subtime = “2005-04-29 15:11:32”;我想得到前2个小时的时间 "2005-04-29 13:11:32"zmy请问怎么样处理subtime
我是新手

解决方案 »

  1.   

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String timeStr = "2005-04-29 13:11:32";
    Date time = sdf.parse(timeStr);
    Date twoHoursAgo = new Date(time.getTime() - 2 * 3600 * 1000);
    System.out.println(sdf.format(twoHoursAgo));
      

  2.   

    java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String timeStr = "2005-04-29 13:11:32";
    Date time = sdf.parse(timeStr);
    Calendar c = Calendar.getInstance();
    c.setTime(time);
    c.add(c.HOUR_OF_DAY,-2);
    Date twoHoursAgo = c.getTime();
    System.out.println(sdf.format(twoHoursAgo));
      

  3.   

    package test;
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    import java.text.*;public class Stime {
      public Stime() {
        try{
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          String timeStr = "2005-04-30 23:11:32";
          Date time = sdf.parse(timeStr);
          Date twoHoursAgo = new Date(time.getTime() + 2 * 3600 * 1000); // 这是后面两个小时的时间,如果想得到前面两个小时的时间,把+号换成-号。
          System.out.println(sdf.format(twoHoursAgo)); // get Time is: 2005-05-01 01:11:32
        }catch(Exception e){
          System.out.println("error : " + e); 
        }
      }
      public static void main(String argu[]){
        Stime stime = new Stime();
      }
    }