简体   繁体   English

如何在Java中将当前时间添加到上一个日期?

[英]How to add current time to a previous date in java?

I was trying to add current time into previous date. 我试图将当前时间添加到上一个日期。 But it was adding in current date with time not with previous date. 但这是在当前日期加上时间,而不是以前的日期。

see my bellow code: 看到我的波纹管代码:

Date startUserDate = ;//this is my previous date object;
startUserDate.setTime(new Date().getTime());// here i'm trying to add current time in previous date.
System.out.println("current time with previous Date :"+startUserDate);

In previous date there is no time and i want to add current time in previous date.I can do this, please help me out. 在以前的日期没有时间,我想在以前的日期中添加当前时间。我可以这样做,请帮帮我。

Use calendar object 使用日历对象

Get instance of calendar object and set your past time to it Date startUserDate = ; 获取日历对象的实例并将其过去的时间设置为它。

    Calendar calendar = Calendar.getInstance();
    calendar.settime(startUserDate);

Create new calendar instance 创建新的日历实例

     Calendar cal = Calendar.getInstance();
     cal.settime(new Date());

format the date to get string representation of time of current date 格式化日期以获取当前日期时间的字符串表示形式

        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        String currentdate =  sdf.format(cal.getTime());

split that string to get hour minute and second object 拆分该字符串以获取时分和第二个对象

                String hh = expiry.split(":")[0];
                String mm = expiry.split(":")[1];
                String ss = expiry.split(":")[2];

add it to the previous calendar object 将其添加到上一个日历对象

    calendar .add(Calendar.HOUR_OF_DAY, hh);
    calendar .add(Calendar.MINUTE, mm);
    calendar .add(Calendar.SECOND, ss);

this date will have current time added to your date 该日期将有当前时间添加到您的日期

   Date newDate = calendar.getTime;

You can do it using DateFormat and String , here's the solution that you need: 您可以使用DateFormatString ,这是您需要的解决方案:

Code: 码:

DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String timeString = df.format(new Date()).substring(10); // 10 is the beginIndex of time here

DateFormat df2 = new SimpleDateFormat("MM/dd/yyyy");
String startUserDateString = df2.format(startUserDate);

startUserDateString = startUserDateString+" "+timeString;
// you will get this format "MM/dd/yyyy HH:mm:ss" 

//then parse the new date here
startUserDate = df.parse(startUserDateString);

Explanation: 说明:

Just convert the current date to a string and then extract the time from it using .substring() method, then convert your userDate to a string concatenate the taken time String to it and finally parse this date to get what you need. 只需将当前日期转换为字符串,然后使用.substring()方法从中提取时间,然后将userDate转换为字符串,即可将所用的时间String与其连接起来,最后解析该日期以获取所需的内容。

Example: 例:

You can see it working in this ideone DEMO . 您可以看到它在此ideone DEMO中运行

Which takes 02/20/2002 in input and returns 02/20/2002 04:36:14 as result. 这需要02/20/2002在输入,并返回02/20/2002 04:36:14的成绩。

Use Calendar : 使用Calendar

  • first set the date/time of the first calendar object to the old date 首先将第一个日历对象的日期/时间设置为旧日期

  • object use as second Calendar object to set the current time on the 对象用作第二个Calendar对象,以设置当前时间

  • first calendar object then convert it back to date 第一个日历对象,然后将其转换回日期

as follow: 如下:

//E.g. for startUserDate 
Date startUserDate = new Date(System.currentTimeMillis() - (24L * 60L * 60L * 1000L) - (60L * 60L * 1000L));//minus 1 day and 1 hour
Calendar calDateThen = Calendar.getInstance();
Calendar calTimeNow = Calendar.getInstance();
calDateThen.setTime(startUserDate);
calDateThen.set(Calendar.HOUR_OF_DAY, calTimeNow.get(Calendar.HOUR_OF_DAY));
calDateThen.set(Calendar.MINUTE, calTimeNow.get(Calendar.MINUTE));
calDateThen.set(Calendar.SECOND, calTimeNow.get(Calendar.SECOND));
startUserDate = calDateThen.getTime();
System.out.println(startUserDate);

The second Calendar object calTimeNow can be replaced with Calendar.getInstance() where it is used. 第二个Calendar对象calTimeNow可以用Calendar.getInstance()替换。

The getTime method returns the number of milliseconds since 1970/01/01 so to get the time portion of the date you can either use a Calendar object or simply use modula arithmetic (using the above milliseconds value and the MAX millseconds in a day) to extract the time portion of the Date. getTime方法返回自1970/01/01以来的毫秒数,因此要获取日期的time部分,可以使用Calendar对象,也可以简单地使用模算术(使用上述毫秒值和一天中的最大毫秒数)来提取日期的时间部分。

Then when you have the time you need to add it to the second date, 然后,如果您有时间需要将其添加到第二个日期,

but seriously, use http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html 但请认真使用http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

and use things like get (HOUR) and get (MINUTE) etc. which then you can use with set (HOUR, val) 并使用诸如get (HOUR)get (MINUTE) ,然后可以与set (HOUR, val)

You need to use Calendar class to perform addition to Date object. 您需要使用Calendar类执行对Date对象的添加。 Date's setTime() will set that time in Date object but not add ie it will overwrite previous date. Date的setTime()将在Date对象中设置该时间,但不会添加该时间,即它将覆盖以前的日期。 new Date().getTime() will not return only time portion but time since Epoch. new Date().getTime()将不仅返回时间部分,而且返回自纪元以来的时间。 Also, how did you manipulated , startUserDate to not have any time (I mean , was it via Calendar or Formatter) ? 另外,您如何操纵startUserDate没有时间(我是说,是通过Calendar还是Formatter)?

See Answer , Time Portion of Date to calculate only time portion, 请参阅答案, 日期的时间部分以仅计算时间部分,

long MILLIS_PER_DAY = 24 * 60 * 60 * 1000; 长MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
Date now = Calendar.getInstance().getTime(); 现在的日期= Calendar.getInstance()。getTime();
long timePortion = now.getTime() % MILLIS_PER_DAY; long timePortion = now.getTime()%MILLIS_PER_DAY;

then you can use something like, cal.add(Calendar.MILLISECOND, (int)timePortion); 那么您可以使用诸如cal.add(Calendar.MILLISECOND, (int)timePortion); where cal is Calendar object corresponding to your startUserDate in your code. 其中cal是与代码中的startUserDate对应的Calendar对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM