Java Android添加2小时到日期字符串
我有一个存储getDate()值的TextView。此getDate()值是日期,但格式为字符串Java Android添加2小时到日期字符串,java,android,date,Java,Android,Date,我有一个存储getDate()值的TextView。此getDate()值是日期,但格式为字符串 textview_device_datetime.setText(data.getDate().replace('T', ' ')); 这就是结果 16-08-2015 16:15:16 但我会在这个字符串日期上加两个小时。 我该怎么办 任何帮助都很好。 谢谢我在这里附上了它的代码和示例 import java.time.*; import java.text.*; import java.u
textview_device_datetime.setText(data.getDate().replace('T', ' '));
这就是结果
16-08-2015 16:15:16
但我会在这个字符串日期上加两个小时。
我该怎么办
任何帮助都很好。
谢谢我在这里附上了它的代码和示例
import java.time.*;
import java.text.*;
import java.util.*;
public class AddTime
{
public static void main(String[] args)
{
String myTime = "16-08-2015 16:15:16";
System.out.println(addHour(myTime,2));
}
public static String addHour(String myTime,int number)
{
try
{
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date d = df.parse(myTime);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.HOUR, number);
String newTime = df.format(cal.getTime());
return newTime;
}
catch(ParseException e)
{
System.out.println(" Parsing Exception");
}
return null;
}
}
通过解析字符串,将字符串转换为
Date
对象,然后在其中添加2小时。再次转换回字符串。有很多问题可以帮助您完成上述步骤:)很高兴看到您希望参与StackOverflow。但请在发布前搜索。您关于向日期时间添加小时数(以及从日期时间值解析/生成字符串)的问题已得到处理。
import java.time.*;
import java.text.*;
import java.util.*;
public class AddTime
{
public static void main(String[] args)
{
String myTime = "16-08-2015 16:15:16";
System.out.println(addHour(myTime,2));
}
public static String addHour(String myTime,int number)
{
try
{
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date d = df.parse(myTime);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.add(Calendar.HOUR, number);
String newTime = df.format(cal.getTime());
return newTime;
}
catch(ParseException e)
{
System.out.println(" Parsing Exception");
}
return null;
}
}