I want to the milliseconds to the next hours. For example
Now time -> 10:01:23 2nd Oct, 2018, Want remaining milliseconds to 11:00:00 2nd Oct, 2018.
The Now time is dynamic, it can be 23:56:56 2nd Oct, 2018 and next hour is at 00:00:00 3rd Oct, 2018.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(startDate.getMillis());
calendar.add(Calendar.HOUR, 1);
I was trying something like this, but it is adding 1 hour to the startDate. But I want exact next hour.
Any help is welcomed.
Since Java8, you can use java.time.LocalDateTime:
LocalDateTime start = LocalDateTime.now();
// Hour + 1, set Minute and Second to 00
LocalDateTime end = start.plusHours(1).truncatedTo(ChronoUnit.HOURS);
// Get Duration
Duration duration = Duration.between(start, end);
long millis = duration.toMillis();
Running just now (2018-10-02T18:44:48.943070 Peking time) I got 911 056 milliseconds.
A simple arithmetic approach:
long hourInMillis = 60 * 60 * 1000;
long startDateInMillis = startDate.getMillis();
long millisSinceLastHourChange = startDateInMillis % hourInMillis;
long millisToNextHourChange = hourInMillis - millisSinceLastHourChange;
works since Java 1 ;-)
EDIT
This approach doesn't take DST or similar changes into account.
tl;dr
Hours on the clock are not always an hour long.
Leverage a time zone to handle such cases.
Duration
.between(
zonedDateTime_Now ,
zonedDateTime_FirstMomentOfHourLater
)
.toMillis()
Beware of anomalies
If you want to account for real-world anomalies in wall-clock time used by your intended time zone, you must specify a time zone. This means using the ZonedDateTime class.
An hour is not always an hour. For example, North Korea recently adjusted its offset-from-UTC by half-an-hour. This means one hour will last only 30 minutes during the adjustment jump. This example of North Korea is only one of the most recent examples. Politicians around the world show a surprising penchant for redefining their time zone(s).
Time zone
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;
Add an hour.
ZonedDateTime hourLater = now.plusHours( 1 ) ;
Truncate to the hour.
ZonedDateTime firstMomentOfNextHour = hourLate.truncatedTo( ChronoUnit.HOURS ) ;
Elapsed time
Calculate elapsed time as a Duration object.
Duration d = Duration.between( now , firstMomentOfNextHour ) ;
The java.time classes use nanosecond resolution, but you asked for milliseconds. So understand that there is data-loss involved in reporting milliseconds.
long milliseconds = d.toMillis() ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project 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.
A java.time solution using ZonedDateTime.until:
ZonedDateTime startDate = ZonedDateTime.now();
LocalDateTime nextHour = startDate.plusHours(1).truncatedTo(ChronoUnit.HOURS);
long msUntillNextHour = startDate.until(nextHour, ChronoUnit.MILLIS);
Related
I want to calculate the sleeping time of user, he should enter when he slept and when he woke up and I should calculate how many hours he slept
For example if the user enter
His sleeping time : 11:00 pm
His waking up time : 7:30 am
The number of sleeping hours should be : 8:30 hrs
Is there any way to make this calculation easily
This is the code
cal.set(Calendar.HOUR_OF_DAY, 11);
cal.set(Calendar.MINUTE, 0);
sleepTimeOnOffDays = cal.getTime();
private long subtractTwoDates(Date date1, Date date2) {
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.setTime(date1);
calendar2.setTime(date2);
long milsecs1 = calendar1.getTimeInMillis();
long milsecs2 = calendar2.getTimeInMillis();
long diff = milsecs2 - milsecs1;
long dhours = diff / (60 * 60 * 1000);
return Math.abs(dhours);
}
From Java SE 8 onwards i would like to suggest using the java.time API. For Android users, java.time is added in API 26+.
Java 8 introduced new APIs for Date and Time to address the shortcomings of the older java.util.Date and java.util.Calendar.
Using the java.time API calculating the duration between 2 date times is very easy.
LocalDateTime localDateTime1 = LocalDateTime.now();
localDateTime1 = localDateTime1.withHour(23).withMinute(0).withSecond(0).withNano(0);
LocalDateTime localDateTime2 = LocalDateTime.now();
localDateTime2 = localDateTime2.plusDays(1).withHour(7).withMinute(30).withSecond(0).withNano(0);
Duration diff = Duration.between(localDateTime1, localDateTime2);
String hms = String.format("%d:%02d:%02d",
diff.toHoursPart(),
diff.toMinutesPart(),
diff.toSecondsPart());
System.out.println(hms);
-----------------------
Console output:
8:30:00
If the java.time API is not available for your project, because for example your project is not yet on API level 26, then i would recommend using the ThreeTen Android Backport API as suggested by #Ole V.V in the comments below.
The Syntax is pretty much the same as the java.time API. The code snippet above works for the ThreeTen Android Backport API as well (like #Basil Bourque already mentioned) with one exception. The Duration class of the ThreeTen Android Backport API unfortunately does not provide helper methods for extracting the hours part, minutes part etc. from the duration object. Instead when you use the backport you need to subtract first the hours, then the minutes from the duration so only the seconds are left:
long hours = diff.toHours();
diff = diff.minusHours(hours);
long minutes = diff.toMinutes();
diff = diff.minusMinutes(minutes);
long seconds = diff.getSeconds();
String hms = String.format("%d:%02d:%02d",
hours,
minutes,
seconds);
Another difference is you need to import the java.time classes from the org.threeten.bp package (not the java.time package).
If you want to use the ThreeTen Backport API, just include it's dependency to your project.
tl;dr
11:00 PM to 7:30 AM = 7.5 or 8.0 or 8.5 or 9.5 or some other number of hours depending on the particular dates and time zone.
Duration.between(
ZonedDateTime.of( 2019 , 1 , 23 , 23 , 0 , 0 , 0 , ZoneId.of( "Africa/Cairo" ) ) ,
ZonedDateTime.of( 2019 , 1 , 24 , 7 , 30 , 0 , 0 , ZoneId.of( "Africa/Cairo" ) )
)
.toString()
See this code run live at IdeOne.com.
PT8H30M
Calculating elapsed time requires date, time-of-day, and time zone
The Answer by Markus Hänsel is headed the right way, but fails to account for anomalies such as Daylight Saving Time (DST).
Your Question is not quite clear. Do you mean to track the general idea of time-of-day using generic 24-hour days? Or do you mean to track actual moments, such as the time slept two days ago, the time slept yesterday, and so on?
If the latter, then you cannot use LocalDateDate as that class cannot, by definition, track moments. The LocalDateTime class lacks any concept of time zone or offset-from-UTC. As such, a LocalDateTime represents potential moments along a range of about 26-27 hours (the range of time zones around the globe).
Given your example of 11:00 pm to 7:30 am, that would mean 8.5 hours in a certain time zone with no anomalies on that date. But on a day of DST cut-over that might mean 7.5 hours (“Spring ahead”), or 9.5 hours (“Fall back”). Or maybe 8.0 hours on day such as last year when North Korea adjusted their clock by a half-hour. Or when in 2007 Venezuela turned back time a half-hour… and then a decade later flipped back again. These changes happen more often than you may realize. Politicians around the globe have shown a penchant for redefining the offset of their time zone(s).
➥ The upshot is that you cannot reliably calculate elapsed time with only the time-of-day. You must use a date and a time zone.
ZoneId
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime
To track moments, use the ZonedDateTime class. This class combines a date, a time-of-day, and a time zone.
LocalDate ldStart = LocalDate.of( 2019 , 1 , 23 ) ;
LocalTime ldStart = LocalTime.of( 23 , 0 ) ;
ZonedDateTime zdtStart = ZonedDateTime.of( ldStart , ltStart , z ) ;
And the stop time.
LocalDate ldStop = LocalDate.of( 2019 , 1 , 24 ) ; // Next day.
LocalTime ldStop = LocalTime.of( 7 , 30 ) ;
ZonedDateTime zdtStop = ZonedDateTime.of( ldStop , ltStop , z ) ;
Calculate elapsed time using Duration class.
Duration d = Duration.between( zdtStart , zdtStop ) ;
ISO 8601
I recommend you not report elapsed time using time-of-day format, HH:MM:SS. Instead use the standard format defined for this purpose, in the ISO 8601 standard.
So, 8.5 hours would be PT8H30M.
The java.time classes use ISO 8601 formats by default when parsing/generating strings.
String output = d.toString() ; // Generate `PT8H30M`.
And parsing.
Duration d = Duration.parse( "PT8H30M" ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project 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.
You can use the SimpleDateFormat for getting the input. I'm using the predefined input, since you wanted the difference calculation between two given times. Here is the code fo you. Please note I have given out the answer for both 24 or 12 hours format.
Getting the value of sleep time and waking up time
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
Date sleepingTime = simpleDateFormat.parse("22:00");
Date wakeUptime = simpleDateFormat.parse("07:00");
For difference is less than zero, this happens in 12 hours format
long difference = sleepingTime.getTime() - wakeUpTime.getTime();
if(difference<0) {
Date dateMax = simpleDateFormat.parse("24:00");
Date dateMin = simpleDateFormat.parse("00:00");
difference=(dateMax.getTime() -sleepingTime.getTime() )+(wakeUpTime.getTime()-
dateMin.getTime());
}
Calculating the difference
//days and minutes are optional
int days = (int) (difference / (1000*60*60*24));
int hours = (int) ((difference - (1000*60*60*24*days)) / (1000*60*60));
int min = (int) (difference - (1000*60*60*24*days) - (1000*60*60*hours)) /
(1000*60);
Log.e("log_tag",hours+" hours");
I hope it will answer your query. Thanks :)
Just Try following line of code to get difference in minutes
import java.util.concurrent.TimeUnit; // predefined method from java 6.
private long subtractTwoDates(Date date1, Date date2) {
Long diffInMinutes=null,diff=null; // just declaration of variables
diff = date1.getTime() - date2.getTime();
diffInMinutes= TimeUnit.MILLISECONDS.toMinutes(diff);
log.info("diff min : "+difInMin);
return diffInMinutes; // returns long value in minutes.
}
Hello I'm trying to convert a string in the format "17:50" to a date in android but when I try to run this code I get the correct hour from the string but the full date is from 1970. I need this date to schedule some local notifications on a given time of the day or in the next day.
String dtStart = "17:50";
SimpleDateFormat format = new SimpleDateFormat("H:mm");
try {
Calendar cal = Calendar.getInstance();
Date date = format.parse(dtStart);
cal.setTime(date);
System.out.println(cal.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
Thu Jan 01 17:50:00 BRT 1970
It's not an error, your code works well. Just if you want to get current date, you have to add the difference between current day and 1st of January 1970.
Your parsed date gives you 17:30 hours, which means 17 * 60 * 60 * 1000 ms + 30 * 60 + 1000 ms.
This way you can find current day: https://stackoverflow.com/a/1908419/4142087
What Anton suggested was correct, and the current day / next day logic is your custom implementation. You have to check current time and if it past that time, jump to setting up the alarm the next day.
java.time
You need a time-of-day class to represent your intended meaning. The legacy date-time classes from the earliest versions of Java lack such a class. The java.sql.Time class pretends to do this, but actually contains a date as well due to poor design decisions.
LocalTime
You want the LocalTime class for a time-of-day value without a date and without a time zone.
It uses a generic 24-hour single-day clock. Adding/subtracting spans of time wraps around the clock since it lacks any concept of dates.
Define a formatting pattern to match your input string.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "H:mm" ) ; // Uppercase `H` means 24-hour clock, lowercase `h` means 12-hour clock.
Parse input string.
String input = "7:50" ;
LocalTime lt = LocalTime.parse( input , f ) ;
Generate a string in standard ISO 8601 format.
String output = lt.toString() ;
07:50
Perhaps your business logic requires assigning the time-of-day to a date. To determine a moment, a point on the timeline, you must also specify a time zone.
LocalDate ld = LocalDate.of( 2018 , Month.MARCH , 27 ) ;
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project 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.
How to get Unix timestamp value only for particular year.
I have a situation where in server side for DOB i store only year. So in android i take Age value and then subtract current year with the age and send that year to server. To send that year i need to convert to Unix timestamp because in server side it stores in Unix timestamp format.
Somebody please help what can be done. I saw some links which uses getTime() and divide it by 1000. But that would be whole year with date and month.
Try this:
Calendar myCal = Calendar.getInstance();
myCal.set(Calendar.YEAR, theYear); // Set the year you want
myCal.set(Calendar.DAY_OF_YEAR, 1);
myCal.set(Calendar.HOUR, 0);
myCal.set(Calendar.MINUTE, 0);
Date theDate = myCal.getTime();
java.time
I get current year and i am converting it to integer and then age which user enters. For example, current year is 2014 and he puts age as 20 so his dob year is 1994. I wanted timestamp value of 1994. And i wanted in GMT.
Apparently you want to the moments at each end of a year.
The modern solution uses the java.time classes that supplanted the terrible old legacy date-time classes.
Parse integer from string
First the year.
String input = "20" ;
integer age = Integer.parseInt( input ) ;
Time zone
Determining a date, and therefore a year, requires a time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your [desired/expected time zone][2] explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Year
Get the current year.
Year currentYear = Year.now( z ) ;
LocalDate & ZonedDateTime
Get the first day of the year as a LocalDate. From that, get the first moment of the day as a ZonedDateTime. A day does not always start at 00:00, so let java.time determine the first moment.
LocalDate firstOfYear = currentYear.atDay( 1 ) ;
ZonedDateTime yearStart = firstOfYear.atStartOfDay( z ) ;
Half-Open
Use Half-Open approach to defining a span-of-time, where beginning is inclusive while the ending is exclusive.
LocalDate firstOfFollowingYear = currentYear.plusYears( 1 ).atDay( 1 ) ;
ZonedDateTime yearStop = firstOfFollowingYear.atStartOfDay( z ) ;
Count-from-epoch
You do not specify what you mean exactly by “Unix timestamp”. I will guess you mean a count of whole seconds since the epoch reference of first moment of 1970 in UTC.
long start = yearStart.toEpochSecond() ;
long stop = yearStop.toEpochSecond() ;
For more discussion, see my Answer to a similar Question.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project 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.
Trying to get Universal Time in java seems to be so difficult. Something like this in C#
DateTime.Now.ToUniversalTime()
seems to be something so difficult. I have code that subtracts a current utc time from a earlier date that is also utc to find the difference in time. But I can't seem to see how to get the current utc time. this is my current code
Date date = new Date();
long difference = date.getTime() - s.getTime();
s is already in utc time because it comes from a source that is passing me the utc time
tl;dr
Current moment in UTC:
Instant.now()
Elapsed time:
Instant then = … ;
Instant now = Instant.now();
Duration duration = Duration.between( then , now ); // For days-hours-minutes-seconds scale.
Render as a count of milliseconds.
long millis = duration.toMillis(); // Possible data-loss in truncating nanoseconds to milliseconds.
java.time
The modern approach to date-time handling in Java is the java.time classes.
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now(); // Current moment in UTC.
The Duration class represents a span of time unattached to the timeline. You can feed in a pair of Instant objects to calculate the number of days, hours, minutes, seconds, and nanoseconds in between.
Duration duration = Duration.between( thisInstant , thatInstant );
Call toString to generate a string in standard ISO 8601 format of PnYnMnDTnHnMnS where P marks the beginning and T separates any years-months-days from the hours-minutes-seconds. For example, an hour and a half is PT1H30M.
You can get the total number of milliseconds in this duration. But beware of possible data-loss. The Instant and Duration classes work in a resolution of nanoseconds, much finer than milliseconds. So extracting milliseconds will truncate any fraction of a second beyond the milliseconds. In other words, rather than having a split second with a decimal representation of up to nine digits, you will have only up to three digits.
long millis = duration.toMillis(); // Possible data-loss in truncating nanoseconds to milliseconds.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
The ThreeTen-Extra project 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.
Joda-Time
UPDATE: The Joda-Time project, now in maintenance mode, advises migration to java.time. Leaving this section intact for history.
Using the Joda-Time 2.4 library.
DateTime nowUtc = DateTime.now( DateTimeZone.UTC );
Best to avoid java.util.Date and .Calendar as they are notoriously troublesome. But if you must, you can convert.
Date date = nowUtc.toDate();
As for getting a difference between date-time values, search StackOverflow for hundreds of answers. Joda-Time offers 3 classes for representing a span of time: Interval, Period, and Duration.
Give this a try:
Date utcDate = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime();
Best,
Loddi
Hmm, no one mentioned System.currentTimeMillis() so i will :) This will return the number of millis since the Unix epoch. This will always be in UTC (e.g. if you call it at the same time in London and in Athens you will get the same values - if the times are set correctly on those devices the timezone shouldn't matter). If you want to obtain a Calendar instance from a number of millis you can just do something like:
Calendar cal = GregorianCalendar.getInstance();
cal.setTimeInMillis(yourMillis);
You can use follwing method to find UTC time:
Calender c= Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Then you can get month,day ,time ,year ant from the calender object..
ex: c.get(Calender.YEAR)
Hope this will help you..
Date is in UTC. There's no time zone attached to Date.
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#getTime()
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object.
What makes you think it's in local time?
Edit: The documentation does say this, so maybe that's the problem:
Although the Date class is intended to reflect coordinated universal
time (UTC), it may not do so exactly, depending on the host
environment of the Java Virtual Machine.
It looks like this might be a good solution:
Calendar c = Calendar.getInstance();
int utcOffset = c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET);
Long utcMilliseconds = c.getTimeInMillis() + utcOffset;
I just started going to university and basically just started using java and I want to know how to make a code that calculates the days between two dates but without the use of programs that take milliseconds and such things that I have seen in other answers.So this is the code I have created but it doesnt work perfectly it misses one day most of the times or something like that.Please I really need your help
Use a SimpleCalendar or GregorianCalendar classes...
but basing on what you posted, I'm unsure how to best suggest using those two... i'll draft a simple example shortly.
After some thought I'll just leave this here Difference in days between two dates in Java?
Taken from: http://www.staff.science.uu.nl/~gent0113/calendar/isocalendar_text5.htm
An approach could be to calculate the number of days from a fixed time for both dates and then just subtract those days. This will give you the difference of days between date 1 and date 2
The following method returns the number of days passed since 0 January 0 CE
public int calculateDate( int day, int month, int year) {
if (month < 3) {
year--;
month = month + 12;
}
return 365 * year + year/4 - year/100 + year/400 + ((month+1) * 306)/10 + (day - 62);
}
In you code now you should calculate the number of days since 0BC for both dates and then subtract them:
public void run() {
....
int dayDifference = calculateDate(day1, month1, year1) - calculateDate(day2, month2, year2);
....
}
tl;dr
java.time.temporal.ChronoUnit.DAYS.between(
LocalDate.of( 2012 , Month.MARCH , 23 ) ,
LocalDate.of( 2012 , Month.MAY , 17 )
)
55
java.time
The modern approach uses java.time classes that supplant the troublesome old legacy date-time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
ChronoUnit.DAYS
To get a count of days between two dates, call on the ChronoUnit enum object DAYS.
long days = ChronoUnit.DAYS.between( earlierLocalDate , laterLocalDate ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project 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.