I want to get current time in my application.
Then i want to add 30 minutes to the current time.
What is the best practice to achieve this?
I am able to get start and stop time from my web service.
eg: ((start time)11:00 am to (stop time) 11:00 pm)
now, i would like to add 30 minutes to the current time till the stop time is reached.
Calendar now = Calendar.getInstance();
now.add(Calendar.MINUTE, 30);
And to output the time you could use
// 24 hours format
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
// AM/PM format
SimpleDateFormat df = new SimpleDateFormat("hh:mm aa");
System.out.println(df.format(now.getTime()));
Use the following:
//get current Time
long currentTime = System.currentTimeMillis();
//now add half an hour, 1 800 000 miliseconds = 30 minutes
long halfAnHourLater = currentTime + 1800000;
System.currentTimeMillis()+(30*60*1000);
Related
I'm working on simple countdown app to tell me how long until certain GMT time.
example:
input: 01-05-2021-02-00-00
output: (if entered time is local) 72 days, 15 hours, 21 mins, 49 secs
output(if entered time is gmt): 72 days, 17 hours, 21 mins, 33 secs
...there should be 16 not 17 hours i believe.
Everything's working fine untill input is between 1. April and 31 October. I give it GMT time and it transforms it to my local (berlin +1) time. If entered time is from mentioned interval it shows +2 hours differencer between berlin and GMT. since it is like this only for certain period of year (any year) it looks weird I don't know what went wrong?
my code:
String result = "";
String date = input;
SimpleDateFormat date_format = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
Date target_date = null;
try {
target_date = date_format.parse(date);
} catch (ParseException e) {
result += e.getMessage();
}
Date now = new Date();
long secs = 0;
if(local_time_radio_btn.isSelected()) {
secs = (target_date.getTime() - now.getTime()) / 1000;
}else {
int offset = target_date.getTimezoneOffset();
long n = 1000 * offset * 60;
long gmt = target_date.getTime() -n;
long now_gmt = now.getTime();
secs = (gmt - now_gmt) / 1000;
}
long days = secs / (60*60*24);
secs = secs % (60*60*24);
long hours = secs / (60*60);
secs = secs % (60*60);
long mins = secs / 60;
secs = secs % 60;
result += days+" days, "+hours+" hours, "+mins+" mins, "+secs +" secs";
java.time
I strongly recommend that you use java.time, the modern Java date and time API, for your date and time work.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-uuuu-HH-mm-ss");
String input = "01-05-2021-02-00-00";
LocalDateTime targetLdt = LocalDateTime.parse(input, formatter);
// German time case
ZoneId zone = ZoneId.of("Europe/Berlin");
ZonedDateTime now = ZonedDateTime.now(zone);
ZonedDateTime target = targetLdt.atZone(zone);
long days = ChronoUnit.DAYS.between(now, target);
ZonedDateTime afterDays = now.plusDays(days);
Duration timeDiff = Duration.between(afterDays, target);
String result = days + " days, " + timeDiff.toHours() + " hours, "
+ timeDiff.toMinutesPart() + " mins, "
+ timeDiff.toSecondsPart() + " secs";
System.out.println(result);
When I ran the code just now (2021-02-18T17:23:35.47 in Berlin), the output was:
71 days, 8 hours, 36 mins, 24 secs
For the UTC (or GMT) case you only need to change one line:
// GMT case
ZoneId zone = ZoneOffset.UTC;
71 days, 9 hours, 36 mins, 24 secs
What went wrong in your code?
First, don’t use SimpleDateFormat and Date as they are poorly designed and long outdated. Even if you insisted on using Date, you should definitely stay away from its getTimezoneOffset method. It has been deprecated since 1997 because it works unreliably across time zones.
Why your code gives an incorrect result in the months you mention is that it counts a day as always 24 hours. On March 28 the EU will transit to summer time (DST), so that day is only 23 hours long, giving rise to an error of exactly 1 hour. On October 31 this year the opposite transisiton may happen (I don’t think it’s been decided yet, but Java thinks that it does), so that day is 25 hours, balancing out for dates after that. Until summer time next year.
Which leads to the next point: don’t do time math yourself. It’s so easy to get wrong. And even when you get it right, it’s hard for the reader to convince oneself that it’s right. You have got a reliable date and time library that is happy to do it for you.
Link
Oracle tutorial: Date Time explaining how to use java.time.
What's weird about your code is that you're first parsing the input string according to a SimpleDateFormat instance that's configured to use local timezone (so, the resulting Date is wrong if the input was meant to be UTC), and then put a lot of effort into re-adjusting the point in time to UTC if that's what the user requested.
Instead, it would be clearer and more robust to have two SimpleDateFormat instances, one with the local timezone, and one with UTC, like:
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
SimpleDateFormat dateFormatUTC = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
dateFormatUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
and select the correct one already when parsing.
By the way, your re-adjusting code uses deprecated features of the Date class, like getTimezoneOffset(), something that should be avoided since Java 1.1.
This question already has answers here:
Android:Display time after adding GMT time zone
(2 answers)
Closed 4 years ago.
I am converting milliseconds to the time of the respective country time format, for example, pakistan, US etc
For example
timeinmilliseconds=1549362600000
So its respective Time formate from which I got these milliseconds is 15:30 or 3:30 in 12 hr format
When I want to convert these milliseconds back to that time
I get 10:30 (Five hrs back)
public String getTimeFromLong(long timeInMilliseconds){
String mytime="";
long minute = (timeInMilliseconds / (1000 * 60)) % 60;
long hour = (timeInMilliseconds / (1000 * 60 * 60)) % 24;
mytime = String.format("%02d:%02d", hour, minute);
return mytime;
}
If I select time 4:00
I converted to that to milliseconds (This part is OK)
And wants the time back from milliseconds but get five hours back
For example, If I select time 9:30
convert it to milliseconds and then to time
I get 4:30
You need to use your local time zone to get the time in your region, the default is being apllied which is the Greenwich Mean Time (GMT). For Pakistan use Asia/Karachi like so:
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("hh:mm");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Karachi"));
Use this method to convert milliseconds into your local time
public String getTime(long time){
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(time);
SimpleDateFormat format = new SimpleDateFormat("hh:mm a");
Date date = new Date(time);
String kTime = format.format(date);
return kTime;
}
Using Java 8 we can do the following.
LocalDateTime dateTime =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
to get date and time
Use below code to get time from long values:
public String getTimeFromLong(long timeInMilliseconds){
// Creating date format
DateFormat simple = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z");
Date result = new Date(timeInMilliseconds);
return simple.format(result);
}
I am trying to convert Account Expires attribute of AD to date. Here is how I am trying to do it:
long adDate = Long.parseLong(adDateStr);
long milliseconds = (adDate / 10000) - DIFF_NET_JAVA_FOR_DATES;
Date date = new Date(milliseconds);
DateFormat mydate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return(mydate.format(date));
The problem is it is adding 1 day to the actual account expires day.
e.g. if the account expires date is 08/01/2106 than the code above is giving 09/01/2016.
Can anyone help me with this?
Just some guesses.
Is the value of DIFF_NET_JAVA_FOR_DATES = 11644473600000L + 24 * 60 * 60 * 1000?
The time in accountExpires and the Date is UTC time (not local).
Is this the reason?
So I'm kinda new to the Calendar/Time/Date stuff in Java but I've read a lot about them on the net.
Here is what I have to do:
I have an external device which sends an Avl Data Packet to my Communication Server and I'm on the parsing process of the Data part.
Somewhere in the Data Packet the device sends a timestamp of 32 bits which I have to parse/translate into the time the Record of the point from the GPS was saved.
The timestamp gives me seconds from 2007.01.01 00:00 UTC
Now here is a sample code that I felt that was the closest one I tried of the rest of the experiments..
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
long now = (long)(TimeStampSeconds.longValue() * 1000);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(2007, 0, 1);
calendar.setTimeInMillis(now);
System.out.println(now + " = " + formatter.format(calendar.getTime()));
After that I found out that the calendar.set doesnt make a new epoch and so the .setTimeInMills doesnt work.Though I get some crazy results like:
Binary Timestamp is : 0000101011000001010110001111011100001111
SECONDS: 46193506063
46193506063000 = 25/10/3433 04:27:43.000
Shouldn't I just be missing just the 37 years between 1970 and 2007??
I want to find a way of finding the time from the seconds I get from the device but they have epoch 1/1/2007 and java has epoch 1/1/1970..
EDIT: What I want is to have time:1/1/2007 PLUS the timestamp's time. Hope I clarified the question a bit..
Someone any ideas??
Thx in Advance
It seems what you want to do is just to add your now value to the Calendar. This is easily done:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
long now = (long)(TimeStampSeconds.longValue() * 1000);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(2007, 0, 1);
calendar.setTimeInMillis(calendar.getTimeInMillis() + now);
System.out.println(now + " = " + formatter.format(calendar.getTime()));
EDIT
Something is weird regarding what your now variable holds. 46193506063 seconds corresponds to 1464.786468258 years according to this time converter.
Assuming you read the input in a timestamp long variable, I'd do something like:
Calendar theirEpoch = Calendar.getInstance();
theirEpoch.set(2007, 0, 1);
Calendar myEpoch = Calendar.getInstance();
myEpoch.set(1970, 0, 1);
long difference = myEpoch.getTimeInMillis() - theirEpoch.getTimeInMillis();
Calendar result = Calendar.getInstance();
result.setTimeInMillis(timestamp + difference);
I didn't test it, but it should give you the idea. Note also that I didn't take time zones into account.
This is the correct way to do what you want:
Calendar cal = Calendar.getInstance();
cal.set(2007, 1, 1, 0 ,0 ,0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.MILLISECOND, theirEpoch);
If their epoch is in seconds, change the last MILISECOND to SECOND.
The easiest thing to do is to use the roll() method of Calendar after setting the time in milliseconds:
calendar.roll(Calendar.YEAR, 37) --> just adds 37 years to your date ;-)
But I think your input data is wrong : if you take the number of seconds that have past since 01/01/2007 until now , it should be about 200 million and not 40 billion like in your example ...
I have two time values. one for the previous login time and one for the current login time.
I have to increase previous time login by one hour. I have used the date format hh:mm:ss.
This is my code snippet.
Date previous_time, current_time;
if(previous_time.before(current_time)){
Log.i("Time Comparision"," true");
}
so instead of the above mentioned if condition, I have to add one hour to the previous_time and do the if condition. How to achieve this?
Calendar calendar = Calendar.getInstance();
calendar.setTime(previous_time);
calendar.add(Calendar.HOUR, 1);
previous_time = calendar.getTime();
// do your comparison
previous_time.setTime(previous_time.getTime() + 60 * 60 * 1000);
or
Date session_expiry = new Date(previous_time.getTime() + 60 * 60 * 1000);
http://download.oracle.com/javase/6/docs/api/java/util/Date.html#getTime%28%29
Please try this code.
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
Date date = Utils.getBookingDate(mBooking.ToTime);
Calendar calendarAdd = Calendar.getInstance();
calendarAdd.setTime(date);
calendarAdd.add(Calendar.HOUR, 1);
toTime = sdf.format(calendarAdd.getTime());
tv_Totime.setText(toTime);
when current time string formate within add 1 hours