I need the current time in milliseconds, so I use Calendar object to retrieve hours and minutes and convert them into milliseconds, but everytime it returns same value, that's the problem.
Calendar calendar = Calendar.getInstance();
int milliseconds = calendar.get(Calendar.HOUR_OF_DAY)*60*60*1000 +
calendar.get(Calendar.MINUTE);
Callendar.getTimeInMillis() and System doesn't work for me cause I can't convert them to daytime. What I need is current daytime but in milliseconds.
use this
System.currentTimeMillis();
You can use
java.util.Calendar.getTimeInMillis()
to get time in millis directly for that particular Calendar instance. If you just need Current time use
System.currentTimeMillis();
https://developer.android.com/reference/java/util/Date.html#getTime()
(new Date()).getTime())
https://developer.android.com/reference/java/lang/System.html#currentTimeMillis()
System.currentTimeMillis());
Both these methods returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
try this use currentTimeMillis() it will Returns the current time in milliseconds.
Long time= System.currentTimeMillis();
Log.i("Time Class ", " Time value in millisecinds "+time);
Read currentTimeMillis.
Returns the current time in milliseconds. Note that while the unit of
time of the return value is a millisecond, the granularity of the
value depends on the underlying operating system and may be larger.
long getTIME= calendar.getTimeInMillis();
Related
I tried a lot with different methods to find out exact solution, but I only get time difference, if I know future date but I want Next Sunday time from current time.
You can try this,
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int saturdayInMonth = calendar.get(Calendar.DAY_OF_MONTH) + (Calendar.SATURDAY - calendar.get(Calendar.DAY_OF_WEEK));
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
saturdayInMonth, 23, 59, 59); // This time will be sunday night 23 hour 59 min and 59 seconds
Date sunday = new Date(calendar.getTimeInMillis() + 1000); //this is 1 second after that seconds that is sunday 00:00.
In Android, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes, together with ThreeTenABP (more on how to use it here). All the classes are in the org.threeten.bp package.
To get a difference between 2 dates, you could use a org.threeten.bp.ZonedDateTime, because this class takes care of Daylight Saving Time changes (and any other offset changes that might happen) and gives the correct/accurate result (if you calculate it without using a timezone, DST changes won't be considered in the calculation).
I also use org.threeten.bp.temporal.TemporalAdjusters class, which has a built-in method to find the next specified day-of-week (by using the constants in the org.threeten.bp.DayOfWeek class).
To get the difference, you can use org.threeten.bp.temporal.ChronoUnit.MILLIS to get the difference in milliseconds (and then you use this value to display in whatever format you want). Or you can use another constants available in org.threeten.bp.temporal.ChronoUnit class (such as MINUTES or HOURS, which will give the difference in minutes or hours - check the javadoc to see all units available).
Another way to get the difference is using a org.threeten.bp.Duration which will contain the number of seconds and nanoseconds between the 2 dates.
// change this to the timezone you need
ZoneId zone = ZoneId.of("Asia/Kolkata");
// get current date in the specified timezone
ZonedDateTime now = ZonedDateTime.now(zone);
// find next Sunday
ZonedDateTime nextSunday = now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
// get the difference in milliseconds
long diffMillis = ChronoUnit.MILLIS.between(now, nextSunday);
// get the difference as a Duration
Duration duration = Duration.between(now, nextSunday);
Note that I used the timezone Asia/Kolkata. The API uses IANA timezones names (always in the format Region/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like IST or PST) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds().
The code above will get nextSunday with the same time (hour/minute/second/nanosecond) as now - except when there's a DST change (in this case, the time is adjusted accordingly).
But if you want to get the remaining time from now until the beginning of the next Sunday, then you have to adjust it to the start of the day before calculating the difference:
// adjust it to the start of the day
nextSunday = nextSunday.toLocalDate().atStartOfDay(zone);
Note that the start of a day is not always midnight - due to DST changes, a day can start at 01:00 AM for example (clocks might be set to 1 hour forward at midnight, making the first hour of the day to be 1 AM). Using atStartOfDay(zone) guarantees that you don't have to worry about that, as the API handles it for you.
If the current date is already a Sunday, what's the result you want?
The code above will get the next Sunday, even if the current date is a Sunday. If you don't want that, you can use TemporalAdjusters.nextOrSame, which returns the same date if it's already a Sunday.
To display the Duration value in time-units (like hours, minutes and seconds), you can do the following:
StringBuilder sb = new StringBuilder();
long seconds = duration.getSeconds();
long hours = seconds / 3600;
append(sb, hours, "hour");
seconds -= (hours * 3600);
long minutes = seconds / 60;
append(sb, minutes, "minute");
seconds -= (minutes * 60);
append(sb, seconds, "second");
append(sb, duration.getNano(), "nanosecond");
System.out.println(sb.toString());
// auxiliary method
public void append(StringBuilder sb, long value, String text) {
if (value > 0) {
if (sb.length() > 0) {
sb.append(" ");
}
sb.append(value).append(" ");
sb.append(text);
if (value > 1) {
sb.append("s"); // append "s" for plural
}
}
}
The result (in my current time) is:
47 hours 44 minutes 43 seconds 148000000 nanoseconds
If you want the milliseconds instead of nanoseconds, you could replace append(sb, duration.getNano(), "nanosecond") with:
// get milliseconds from getNano() value
append(sb, duration.getNano() / 1000000, "millisecond");
I am making a simple alarm clock application that mimics the default alarm app that comes with Android Lollipop.
The set*( ) methods of an AlarmManager require the date on which the alarm should be fired as a Unix epoch.
The UI is rather simple with a TimePicker.
So, given the current time and the time the user has selected from TimePicker, how do I figure out the time in milliseconds when the alarm should be fired?
Update:
There are two cases I run into:
Selecting the time that is after the current time:
Assume it is 11am and the user selects the time from the time picker as 03pm. In this case, I know that the alarm should be scheduled for the same day.
Selecting the time that is before the current time:
Assume it is 11am and the user selects the time from the time picker as 10am. In this case, I know that the alarm should be scheduled for the next day's 10am.
Ok here you go:
// Get the current time
final Date currentTime = new Date();
// Set the hours and minutes from the time picker against todays date
final Calendar selectedTime = Calendar.getInstance();
selectedTime.set(Calendar.HOUR_OF_DAY, hourFromTimePicker);
selectedTime.set(Calendar.MINUTE, minuteFromTimePicker);
// If the current date is greater than the hour and minute from time picker add one day
if (currentTime.getTime() > selectedTime.getTime().getTime()) {
selectedTime.add(Calendar.DAY_OF_YEAR, 1);
}
// Schedule the alarm
//AlarmManager.set(selectedTime.getTime().getTime());
if you store data in java Date object:
long getTime( )
Returns the number of milliseconds that have elapsed since January 1, 1970.just subtract.
Another way if you look only at time within day:
int ms = 1000*SECONDS + 1000*60*MINUTES + 1000*60*60*HOURS
I would use a android.text.format.Time class
call the setters on the Time class to set the Hour, Minute, Second, etc. The Hours are in 24H time, so if the current hour > selected hour then you know to increment days by 1
Finally, call Time#toMillis(boolean ignoreDst) to get the system time in millis, and pass that to AlarmManager
EDIT: GregorianCalendar should be used instead.
I know this is very simple question but I am not able to do it.
I have a code that gets current time but this time is not accurate.
booking.CreateDateTime = DateTime.Now.ToUniversalTime();
When I am booking at 12:00 then in database stores 1:00 that means 1 hour difference.
How can I get accurate time?
Use System.currentTimeMillis() to get the current GMT time in mili seconds since epoch.
Then you can use this value to create a new Date or Calendar object and localize it wherever the user is.
I'm not familiar with what you have there, but ToUniversalTime suggests to me that this is adjusting your time to some fixed time zone (probably GMT)
Use a Date to get the time right now, and then a Calendar to do any time zone changes on it that you want.
Example, assuming CreateDateTime is actually a string of what you said it was:
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
booking.CreateDateTime = calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE));
I am sending Sms from emulator control to emulator.. but it shows time in some different format. Can Anyone Help me understand that code or format. Here is the pic
Its probably using the System.currentTimeMillis() function for accessing the time, what returns the current time in milliseconds. If you want your date formatted, then use:
long time = System.currentTimeMillis();
String timeString = new Date(time).toLocaleString();
Or if you just need the time part from it, like in the example you have shown, then:
SimpleDateFormat formater = new SimpleDateFormat("h:mm a");
String timeString = formater.format(new Date(time)); //time is the current time as a long value;
As for how the date is stored:
System.currentTimeMillis()
Returns the difference, measured in milliseconds, between the current
time and midnight, January 1, 1970 UTC.
This means, that the long number you get, is the passed milliseconds since January 1, 1970.
From this value its pretty easy to count the current year, month day, etc...
As you can see in my previous example, you can conver this long value to a Date object, by passing it to the Date() constructor, and you can convert a Date object to a long value using:
long time = dateObject.getTime();
I hope this helps!
I am trying to display in a TextView when my application last updated (e.g., "Last updated at 12:13). I am trying to use a Calendar instance and I thought I understood it correctly but I seem to be having trouble. I know to get an instance I use the method Calendar.getInstance(). And then to get the hour and minute I was using Calendar.get(Calendar.HOUR) and Calendar.get(Calendar.MINUTE). My minute field returns correctly but Calendar.HOUR is returning the hour on a 24 hour clock and I want a 12 hour clock. I thought HOUR_OF_DAY was 24 hour clock. Where am I going wrong?
Here is the code I'm using:
Calendar rightNow = Calendar.getInstance();
mTv.setText("Refreshed! Last updated " +
rightNow.get(Calendar.HOUR) + ":" +
rightNow.get(Calendar.MINUTE) + ".");
mTv is my TextView that I'm updating. Thanks for any help.
Also, it would be ideal if I could say "Last updated 5 minutes ago." instead of "Last updated at 12:13pm". But I'm not sure the best way to have this update each minute without draining resources or the battery...?
I'd recommend using SimpleDateFormat in combination with the Date class for formatting the time:
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("K:mm a");
String formattedTime = sdf.format(now);
Short explanation how it works:
You create a SimpleDateFormat object and pass a String to it's construtor which tells it how to format every time/date object that gets passed to the format() function of it.
There are plenty of constants/letters which represent a special time object (e.g. seconds, an AM/PM marker, .. see the class documentation for the full list).
"K:mm a" means a "11:42 AM" format - one or two digits for the hour (depending on its value) in a 12 hour format, always two digits for minutes (mm) and either AM or PM (a), depending on the time.
After you did that, just pass a Date object to the format() function, and you'll get a formatted string. Note that a Date just holds one single point in time, if you create it from the constructor with no arguments ("= new Date()") it uses the current time. If you need another time, you can pass a long argument with the millis, you may get that from Calendar.getTimeInMillis().
As of implementing the "updated XY minutes ago function" - yes you'd have to update this every minute and you have to calculate the difference between the update and the current time. I'd say it's not worth it from a battery and extra work perspective.
If your app uses standard short update cycles (e.g. every hour or somthing along those lines) and is not fullscreen, the user has a visible clock on top/bottom of his screen. If he really wants to check how long it was since the update, he can take a short look and compare (mostly just minutes or hours/minutes). And IMHO thats no inconvinience for a user, at least it would not for me. I'd just compare without thinking about that. But I tend to kill apps which waste my battery for no useful reason.
Also note that not everybody uses a 12-hour format. To get a localized time format depending on users settings/country use DateFormat.getTimeInstance(). This returns a DateFormat, but this works like the SimpleDateFormat, just pass a time to format().
Use Calendar.HOUR_OF_DAY for 24h clock
Calendar rightNow = Calendar.getInstance();
mTv.setText("Refreshed! Last updated " +
rightNow.get(Calendar.HOUR_OF_DAY) + ":" +
rightNow.get(Calendar.MINUTE) + ".");
You can update editText in each minute using a thread like following
Thread t = new Thread(){
public void run() {
Calendar oldTime = Calendar.getInstance();
oldMinute = oldTime .get(Calendar.MINUTE);
while(true) {
Calendar rightNow= Calendar.getInstance();
newMinute = rightNow.get(Calendar.MINUTE);
if(newMinute != oldMinute) {
oldMinute = newMinute;
mTv.setText("Refreshed! Last updated " +
rightNow.get(Calendar.HOUR) + ":" +
rightNow.get(Calendar.MINUTE) + ".");
}
}
}
t.start();
Well, Calendar.get(Calendar.HOUR) should be returning 12-hour time, but if you wanted to produce your slightly nicer text, you can use the TimeUnit class for parsing simplicity.
long millis = Calendar.getInstance().getTimeInMillis();
String.format("Last updated %d min, %d sec ago.",
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);