如何将字符串转换为时间格式并添加两个小时 [英] how to convert string into time format and add two hours

查看:441
本文介绍了如何将字符串转换为时间格式并添加两个小时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中有以下要求。



我有一个输入字段,名称为 startDate 和用户输入格式 YYYY-MM-DD HH:MM:SS
我需要在 startDate 字段中为用户输入添加两个小时。我如何做到这一点。



提前感谢

解决方案

可以使用SimpleDateFormat将String转换为Date。然后,您有两个选项,




  • 创建一个Calendar对象,然后使用它添加两个小时,或

  • 从该日期对象获取毫秒的时间,并添加两个小时,如(2 * 60 * 60 * 1000)

      SimpleDateFormat df = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss); 

    //替换开始日期字符串
    日期d = df.parse(2008-04-16 00:05:05);
    日历gc = new GregorianCalendar();
    gc.setTime(d);
    gc.add(Calendar.HOUR,2);
    日期d2 = gc.getTime();

     code> SimpleDateFormat df = new SimpleDateFormat(yyyy-MM-dd HH:mm:ss); 

    //替换开始日期字符串
    日期d = df.parse(2008-04-16 00:05:05);
    长时间= d.getTime();
    time + =(2 * 60 * 60 * 1000);
    日期d2 =新日期(时间);




看看这些教程。 p>


I have the following requirement in the project.

I have a input field by name startDate and user enters in the format YYYY-MM-DD HH:MM:SS. I need to add two hours for the user input in the startDate field. how can i do it.

Thanks in advance

解决方案

You can use SimpleDateFormat to convert the String to Date. And after that you have two options,

  • Make a Calendar object and and then use that to add two hours, or
  • get the time in millisecond from that date object, and add two hours like, (2 * 60 * 60 * 1000)

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    // replace with your start date string
    Date d = df.parse("2008-04-16 00:05:05"); 
    Calendar gc = new GregorianCalendar();
    gc.setTime(d);
    gc.add(Calendar.HOUR, 2);
    Date d2 = gc.getTime();
    

    Or,

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    // replace with your start date string
    Date d = df.parse("2008-04-16 00:05:05");
    Long time = d.getTime();
    time +=(2*60*60*1000);
    Date d2 = new Date(time);
    

Have a look to these tutorials.

这篇关于如何将字符串转换为时间格式并添加两个小时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆