如何将字符串转换为时间格式并添加两个小时

32

在项目中,我有以下需求。

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

提前致谢。


5
误读为“星际日期”。我甚至不喜欢《星际迷航》。 - Jon Purdy
9个回答

46

你可以使用SimpleDateFormat将字符串转换为日期。之后有两个选项:

  • 创建一个Calendar对象,然后使用它添加两个小时;或者
  • 从该日期对象中获取毫秒数,然后再加上两个小时,例如(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();

或者,

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);

请查看这些教程。


33

作为Joda Time库的粉丝,以下是如何使用Joda DateTime来实现:

import org.joda.time.format.*;
import org.joda.time.*;

...    

String dateString = "2009-04-17 10:41:33";

// parse the string
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dateTime = formatter.parseDateTime(dateString);

// add two hours
dateTime = dateTime.plusHours(2); // easier than mucking about with Calendar and constants

System.out.println(dateTime);
如果你仍需要在此转换前/后使用java.util.Date对象,Joda DateTime API提供了一些易于翻译的方法toDate()toCalendar()。相比Java Date/Calendar API,Joda API提供了更多便利性。

2
每个人都应该成为Joda的粉丝。这是我使用过的最好的库。+1 - WolfmanDragon
我完全同意Rob Hruska和WolfmanDragon的观点。这个库使用起来非常简单,我也建议在每个需要日期/时间操作的Java项目中都加入它(几乎所有项目都需要 :))。 - рüффп
1
我同意 @ruffp 的观点,在Scala中运作得非常好,而且没有括号的限制,效果非常棒。 - virtualeyes
FYI,Joda-Time 项目现已进入 维护模式,团队建议迁移到 java.time 类。请参阅 Oracle 的教程 - Basil Bourque

6

试试这个,我测试过了,工作得很好。

Date date = null;
String str = "2012/07/25 12:00:00";
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
date = formatter.parse(str);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR, 2);
System.out.println(calendar.getTime());  // Output : Wed Jul 25 14:00:00 IST 2012

如果您想将输入类型转换,则还需添加以下代码
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
str=formatter.format(calendar.getTime());
System.out.println(str);  // Output : 2012-07-25 14:00:00

4
使用SimpleDateFormat类的parse()方法。该方法将返回一个Date对象。然后,您可以为此Date创建一个Calendar对象,并向其添加2小时。
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = formatter.parse(theDateToParse);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, 2);
cal.getTime(); // This will give you the time you want.

我正在提供代码,请告诉我它是否正确。日历EDate = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); EDate.setTime(sdf.parse(enddate)); EDate.add(Calendar.Hour, 1); - user48094
你拥有的日期字符串是AM还是PM?因为你使用了小写的hh表示小时,同时又用了Calendar.HOUR。我的代码使用的是24小时制。 - Bhushan Bhangale

3
//the parsed time zone offset:
DateTimeFormatter dateFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String fromDateTimeObj = "2011-01-03T12:00:00.000-0800";
DateTime fromDatetime = dateFormat.withOffsetParsed().parseDateTime(fromDateTimeObj);

1

tl;dr

LocalDateTime.parse( 
    "2018-01-23 01:23:45".replace( " " , "T" )  
).plusHours( 2 )

java.time

现代方法使用Java 8、Java 9及更高版本中添加的java.time类。

用户以YYYY-MM-DD HH:MM:SS格式输入

将该输入字符串解析为日期时间对象。您的格式接近符合标准ISO 8601格式,java.time类默认用于解析/生成字符串。要完全符合,请将中间的空格替换为T
String input = "2018-01-23 01:23:45".replace( " " , "T" ) ; // Yields: 2018-01-23T01:23:45

如果您的输入缺少任何时区或UTC偏移量指示符,请将其解析为LocalDateTime

LocalDateTime ldt = LocalDateTime.parse( input ) ;

增加两小时

Java.time类可以为您进行计算。

LocalDateTime twoHoursLater = ldt.plusHours( 2 ) ;

时区

请注意,LocalDateTime并不代表一个时刻或时间轴上的某个点。如果没有时区或与UTC的偏移量的上下文,它就没有真正的含义。名称中的“本地”部分表示任何地方或没有地方,而不是特定的某个地方。仅仅说“1月21日中午”可能意味着新西兰奥克兰市中午,这比法国巴黎市中午早几个小时。

要定义一个实际的时刻,您必须指定一个时区或偏移量。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;  // Define an actual moment, a point on the timeline by giving a context with time zone.

如果您确定了特定的时区,请在添加两个小时之前应用它。当进行计算时,LocalDateTime类假定简单的通用24小时制日历。但是,在不同的时区和日期,一天可能长23或25个小时,或者可能有其他长度。因此,在有时区的上下文中获得正确的结果,应将小时数添加到您的ZonedDateTime而不是LocalDateTime中。

关于java.time

java.time框架是Java 8及以上版本内置的。这些类取代了令人头痛的旧遗留日期时间类,例如java.util.DateCalendarSimpleDateFormat

Joda-Time项目现在处于维护模式,建议迁移到java.time类。

要了解更多内容,请参阅Oracle教程。在Stack Overflow上搜索许多示例和解释。规范是JSR 310
在哪里获取java.time类?

ThreeTen-Extra 项目扩展了 java.time 的附加类。该项目是 java.time 可能未来添加的一个试验场。您可能会在这里找到一些有用的类,例如 Interval, YearWeek, YearQuarter更多


1

这个例子是关于日期时间和时区(字符串值)的求和。

String DateVal = "2015-03-26 12:00:00";
String TimeVal = "02:00:00";

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");

Date reslt = sdf.parse( DateVal );
Date timeZ = sdf2.parse( TimeVal );
//Increase Date Time
reslt.setHours( reslt.getHours() + timeZ.getHours());
reslt.setMinutes( reslt.getMinutes() + timeZ.getMinutes());
reslt.setSeconds( reslt.getSeconds() + timeZ.getSeconds());

System.printLn.out( sdf.format(reslt) );//Result(+2 Hours):  2015-03-26 14:00:00 

感谢 :)

1

添加两个时间的基本程序:
您可以使用if else根据需要修改hour:min:sec。
此程序展示了如何将两个对象的值相加并返回到另一个对象中。

class demo
{private int hour,min,sec;
    void input(int hour,int min,int sec)
    {this.hour=hour;
    this.min=min;
    this.sec=sec;

    }
    demo add(demo d2)//demo  because we are returning object
    {   demo obj=new demo();
    obj.hour=hour+d2.hour;
    obj.min=min+d2.min;
    obj.sec=sec+d2.sec;
    return obj;//Returning object and later on it gets allocated to demo d3                    
    }
    void display()
    {
        System.out.println(hour+":"+min+":"+sec);
    }
    public static  void main(String args[])
    {
        demo d1=new demo();
        demo d2=new demo();
        d1.input(2, 5, 10);
        d2.input(3, 3, 3);
        demo d3=d1.add(d2);//Note another object is created
        d3.display();


    }

}

修改时间添加程序

12 && hour < 24) ? (hour - 12) : hour; this.min = (min > 60) ? 0 : min; this.sec = (sec > 60) ? 0 : sec; } demo add(demo d2) { demo obj = new demo(); obj.hour = hour + d2.hour; obj.min = min + d2.min; obj.sec = sec + d2.sec; if (obj.sec > 60) { obj.sec -= 60; obj.min++; } if (obj.min > 60) { obj.min -= 60; obj.hour++; } return obj; } void display() { System.out.println(hour + ":" + min + ":" + sec); } public static void main(String args[]) { demo d1 = new demo(); demo d2 = new demo(); d1.input(12, 55, 55); d2.input(12, 7, 6); demo d3 = d1.add(d2); d3.display(); } }

1
这将会给你想要的时间(例如:21:31 PM)。
//Add 2 Hours to just TIME
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss a");
Date date2 = formatter.parse("19:31:51 PM");
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
cal2.add(Calendar.HOUR_OF_DAY, 2);
SimpleDateFormat printTimeFormat = new SimpleDateFormat("HH:mm a");
System.out.println(printTimeFormat.format(cal2.getTime())); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接