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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/759036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:07:47  来源:igfitidea点击:

how to convert string into time format and add two hours

javadatetime

提问by user48094

I have the following requirement in the project.

我在项目中有以下要求。

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

我有一个按名称输入的字段startDate,用户输入格式YYYY-MM-DD HH:MM:SS。我需要为startDate字段中的用户输入添加两个小时。我该怎么做。

Thanks in advance

提前致谢

回答by Adeel Ansari

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

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

  • 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);
    
  • 创建一个 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);
    

Have a look to these tutorials.

看看这些教程。

回答by Bhushan Bhangale

Use the SimpleDateFormatclass parse()method. This method will return a Dateobject. You can then create a Calendarobject for this Dateand add 2 hours to it.

使用SimpleDateFormatparse()方法。此方法将返回一个Date对象。然后,您可以Calendar为此创建一个对象并为其Date添加 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.

回答by Rob Hruska

Being a fan of the Joda Timelibrary, here's how you can do it that way using a Joda DateTime:

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

If you still need to use java.util.Dateobjects before/after this conversion, the Joda DateTimeAPI provides some easy toDate()and toCalendar()methods for easy translation.

如果您仍然需要使用java.util.Date前对象/这种转换之后,乔达DateTimeAPI提供了一些方便toDate()toCalendar()容易的翻译方法。

The Joda API provides so much more in the way of convenience over the Java Date/Calendar API.

与 Java 日期/日历 API 相比,Joda API 提供了更多的便利。

回答by Amit Kushwaha

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

回答by Lalit Bhudiya

Try this one, I test it, working fine

试试这个,我测试过,工作正常

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

If you want to convert in your input type than add this code also

如果你想在你的输入类型中转换而不是添加这个代码

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

回答by Isabella Engineer

Basic program of adding two times:
You can modify hour:min:sec as per your need using if else.
This program shows you how you can add values from two objects and return in another object.

添加两次的基本程序:
您可以根据需要使用 if else 修改小时:分钟:秒。
该程序向您展示了如何从两个对象中添加值并在另一个对象中返回。

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


    }

}

Modified Time Addition Program

修改时间加法程序

class demo {private int hour,min,sec; void input(int hour,int min,int sec) {this.hour=(hour>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(); } }

回答by Ferhat KO?ER

This example is a Sum for Date time and Time Zone(String Values)

此示例是日期时间和时区的总和(字符串值)

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 

Thanks :)

谢谢 :)

回答by bnhs

This will give you the time you want (eg: 21:31 PM)

这会给你你想要的时间(例如: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())); 

回答by Basil Bourque

tl;dr

tl;博士

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

java.time

时间

The modern approach uses the java.timeclasses added to Java 8, Java 9, and later.

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

user enters in the format YYYY-MM-DD HH:MM:SS

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

Parse that input string into a date-time object. Your format is close to complying with standard ISO 8601 format, used by default in the java.time classes for parsing/generating strings. To fully comply, replace the SPACE in the middle with a T.

将该输入字符串解析为日期时间对象。您的格式接近符合标准 ISO 8601 格式,默认情况下在 java.time 类中用于解析/生成字符串。要完全遵守,请将中间的 SPACE 替换为T.

String input = "2018-01-23 01:23:45".replace( " " , "T" ) ; // Yields: 2018-01-23T01:23:45

Parse as a LocalDateTimegiven that your input lacks any indicator of time zone or offset-from-UTC.

解析为LocalDateTime您的输入缺少任何时区或UTC 偏移量指标。

LocalDateTime ldt = LocalDateTime.parse( input ) ;

add two hours

加两个小时

The java.time classes can do the math for you.

java.time 类可以为您做数学计算。

LocalDateTime twoHoursLater = ldt.plusHours( 2 ) ;

Time Zone

时区

Be aware that a LocalDateTimedoes notrepresent a moment, a point on the timeline. Without the context of a time zone or offset-from-UTC, it has no real meaning. The “Local” part of the name means anylocality or nolocality, rather than any one particular locality. Just saying "noon on Jan 21st" could mean noon in Auckland, New Zealand which happens several hours earlier than noon in Paris France.

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

To define an actual moment, you must specify a zone or offset.

要定义实际力矩,您必须指定区域或偏移量。

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.

If you know the intended time zone for certain, apply it beforeadding the two hours. The LocalDateTimeclass assumes simple generic 24-hour days when doing the math. But in various time zones on various dates, days may be 23 or 25 hours long, or may be other lengths. So, for correct results in a zoned context, add the hours to your ZonedDateTimerather than LocalDateTime.

如果您确实知道预期的时区,请添加两个小时之前应用它。该LocalDateTime课程在进行数学运算时假设简单的通用 24 小时制。但在不同日期的不同时区中,天可能是 23 或 25 小时长,也可能是其他长度。因此,为了在分区上下文中获得正确结果,请将小时数添加到您的ZonedDateTime而不是LocalDateTime.



About java.time

关于 java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

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

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多