How to display only time in UNIX? I only using java6. Can't upgrade the java cause have some inconvience cause.
DateFormat dfm = new SimpleDateFormat("yyyymmdd");
Calendar calConvert = Calendar.getInstance();
String currDate = dateFormat.format(calConvert);
int year = Integer.parseInt(currDate .substring(0, 4));
int month = Integer.parseInt(currDate .substring(4, 6));
int day = Integer.parseInt(currDate .substring(6));
int hour = Integer.parseInt(candle2.sTransTimeTo.substring(0, 2));
int minute = Integer.parseInt(candle2.sTransTimeTo.substring(2, 4));
int second = Integer.parseInt(candle2.sTransTimeTo.substring(4));
calConvert.setTimeZone(TimeZone.getTimeZone("GMT + 8:00"));
calConvert.set(year, month, day);
calConvert.set(Calendar.HOUR, hour);
calConvert.set(Calendar.MINUTE, minute);
calConvert.set(Calendar.SECOND, second);
candle2.sTransTimeTo = Long.toString(calConvert.getTimeInMillis() / 1000);
candle2.sTransTimeTo is the time we need to display.
How to show only time?
if i do as below coding:
calConvert.setTimeZone(TimeZone.getTimeZone("GMT + 8:00"));
calConvert.set(Calendar.HOUR, hour);
calConvert.set(Calendar.MINUTE, minute);
calConvert.set(Calendar.SECOND, second);
candle2.sTransTimeTo = Long.toString(calConvert.getTimeInMillis() / 1000);
Please read the official Java documentation.
But for now the code below will give you a head start.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FormattedDateTimeOnly {
public static void main(String[] args){
DateFormat yourDateFormat = new SimpleDateFormat("hh:mm:ss a");
Date date = new Date();
String time = yourDateFormat.format(date);
System.out.println(time);
}
}
Have you tried this?
//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal=Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
From the question How to change TIMEZONE for a java.util.Calendar/Date
To display the current local time you can simply do this:
DateFormat dateFormat = new SimpleDateFormat("HH:mm");
String text = dateFormat.format(new Date());
System.out.println(text);
tl;dr
To get count of whole seconds since the Unix epoch of 1970-01-01T00:00:00Z.
Instant.now()
.getEpochSecond()
Details
This has been covered many times already on Stack Overflow, so briefly…
Use modern java.time classes, not the troublesome legacy Date/Calendar classes.
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() ;
Use true time zones when known, rather the mere offset-from-UTC.
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(!).
Assign a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Asia/Brunei" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
To extract only the date, without a time-of-day and without a time zone, ask for a LocalDate.
LocalDate ld = zdt.toLocalDate() ;
To extract only the time-of-day, convert to a LocalTime.
LocalTime lt = zdt.toLocalTime() ;
To generate strings in standard ISO 8601 format, call toString on any java.time object. For other formats, see DateTimeFormatter and DateTimeFormatterBuilder.
➠ To get the number of seconds from the epoch reference date of 1970-01-01T00:00Z, interrogate the ZonedDateTime. Some call this Unix Time.
long secondsFromEpoch = zdt.toEpochSecond() ;
To get the number of seconds from midnight, use Duration. Do not assume midnight is 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day might start at a time such as 01:00:00. Ask java.time to determine the first moment of the day.
long secondsSinceStartOfDay =
Duration.between(
zdt.atStartOfDay( z ) , // Get first moment of the day, may or may not be `00:00:00`.
zdt
).getSeconds() ; // Render duration as a total number of seconds.
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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
Related
I have picked up a date from date picker and another from currently system time. when I want to subtract 2 date what one of them is before 2000 I get some invalid answer for year. how can I resolve it?
public class Duration {
private int year,month,day,hour,min,seconds;
public Duration(long endTime, long startTime){
Calendar calendar1=new GregorianCalendar();
calendar1.setTimeInMillis(endTime);
Calendar calendar=new GregorianCalendar();
calendar.setTimeInMillis(startTime);
this.year=calendar1.get(Calendar.YEAR)-calendar.get(Calendar.YEAR);
this.month=calendar1.get(Calendar.MONTH)-calendar.get(Calendar.MONTH);
this.day=calendar1.get(Calendar.DAY_OF_MONTH)-calendar.get(Calendar.DAY_OF_MONTH);
this.hour=calendar1.get(Calendar.HOUR)-calendar.get(Calendar.HOUR);
this.min=calendar1.get(Calendar.MINUTE)-calendar.get(Calendar.MINUTE);
this.seconds=calendar1.get(Calendar.SECOND)-calendar.get(Calendar.SECOND);
System.out.println(toString());
}
public int getDay() {
return day;
}
public int getHour() {
return hour;
}
public int getMin() {
return min;
}
public int getMonth() {
return month;
}
public int getSeconds() {
return seconds;
}
public int getYear() {
return year;
}
#Override
public String toString() {
return year+" "+month+" "+day+" "+hour+" "+min+" "+seconds;
}
}
when I want to subtract a date in 1998/2/jan from current time I get this result :
-1879 1 3 10 24 34
what the year isn't correctly.
LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();
You will get the number of days in long format. Also refer this answer by Mark Byers.
Method: 1
try {
DateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
Date date1 = new java.util.Date();
Date date2 = df.parse("04-02-2019 12:00:00");
long diff = date2.getTime() - date1.getTime();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(diff);
int year = cal.get(Calendar.YEAR);
Log.e("Diff Year" , year+ " --" + diff);
Log.e("Diff Value" , date1.getTime() + " -- " + date2.getTime() + " --" + diff);
} catch (ParseException e){
Log.e("Diff Value", "Exception", e.getMessage().toString());
}
Method: 2
LocalDate d1 = LocalDate.parse("2017-04-02",
DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-04-04",
DateTimeFormatter.ISO_LOCAL_DATE);
Duration dateDifference = Duration.between(d1.atStartOfDay(),
d2.atStartOfDay());
long dayDifference = dateDifference.toDays();
Subtract Two dates and add difference value in Calendar Object and
retrieve Year value from its Object.
tl;dr
LocalDate // Represent a date-only value, without time-of-day and without time zone.
.of( 1999 , 1 , 23 ) // Use factory methods to instantiate rather than constructors, in the *java.time* classes.
.minusWeeks( 12 ) // Do date-math with `plus…` and `…minus` methods.
.toString() // Generate text as a `String` object with text representing the date value in standard ISO 8601 format: YYYY-MM-DD
See this code run live at IdeOne.com.
1998-10-31
Avoid legacy date-time classes
Never use Calendar or Date classes. Those terrible classes were supplanted years ago by the java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
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 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" ) ;
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 code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
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. Ditto for Year & YearMonth.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
Period
To represent a span-of-time in terms of years-months-days, use Period.
Period p = Period.ofDays( 5 ) ;
Date-time math
You can perform addition and subtraction of date-time values in java.time by calling the plus… and minus… methods.
LocalDate later = ldt.plus( p ) ;
Duration
If you want to represent a span-of-time in terms of days (24-hour chunks of time, unrelated to calendar), hours, minutes, seconds, and fractional second, use Duration.
Year
Your question not clear, but seems to be about the year 2000. There is nothing special about that year with the java.time classes.
You can interrogate the java.time classes for their year value.
int year = ld.getYear() ;
if( year < 2000 ) { … }
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.
I want my step counter to display steps from 12 am to 12 am I cant find a way to that is working. I am using Google's fitness API
here's the code:
Calendar cal = Calendar.getInstance();
Date today = new Date();
cal.setTime(today);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.MONTH, -1);
long startTime = cal.getTimeInMillis();
java.text.DateFormat dateFormat = DateFormat.getDateInstance();
Log.e("History", "Range Start: " + dateFormat.format(startTime));
Log.e("History", "Range End: " + dateFormat.format(endTime));
//Check how many steps were walked and recorded in the last 7 days
final DataReadRequest readRequest = new DataReadRequest.Builder()
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
.bucketByTime(1, TimeUnit.DAYS)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build();
final DataReadResult dataReadResult = Fitness.HistoryApi.readData(mGoogleApiClient, readRequest).await(1,TimeUnit.MINUTES);
java.time
You are using terrible old date-time classes that were supplanted years ago by the java.time classes defined in JSR 310.
LocalDate
First, get the date of interest. If you want “today”, you must specify a time zone.
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
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 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" ) ;
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.
First moment of the day
12 am to 12 am
A day does not always run from 12 AM to 12 AM!
Never assume when a day begins or ends. A day is not always 24 hours long, it can be 23, 23.5, 25, or any other number of hours dreamed up by the politicians defining the time zone. In some zones on some dates, the day may not start at 00:00, it may start at some other time such as 01:00. Let java.time determine when a day begins and ends.
Half-Open
Generally the best approach in defining a span-of-time is the Half-Open approach. In this approach, the beginning is inclusive while the ending is exclusive. This avoids the challenge of trying to determine the exact split-second end of the day. A day starts at the first moment of one date and runs up to, but does not include, the first moment of the next date.
ZonedDateTime zdtStart = ld.atStartOfDay( z ) ; // First moment of the day as seen in the wall-clock time used by the people of a particular region as defined arbitrarily by their politicians (a time zone).
ZonedDateTime zdtStop = ld.plusDays( 1 ).atStartOfDay( 1 ) ; // First moment of the day of the *following* date.
Epoch reference date, & granularity
The Google API for DataReadRequest.Builder::setTimeRange takes count of some granularity since some epoch reference date. Unfortunately, nether the limit of the granularity nor the epoch reference is specified – and there are many epoch references in use.
I will take a guess at seconds being the finest granularity, and guess at 1970-01-01T00:00Z being the epoch reference. This epoch is used by the java.time classes and by the terrible old java.util.Date class.
long secondsSinceEpoch_Start = zdtStart.toEpochSecond() ;
long secondsSinceEpoch_Stop = zdtStop.toEpochSecond() ;
Make your call to the API.
…
.setTimeRange(
secondsSinceEpoch_Start ,
secondsSinceEpoch_Stop ,
TimeUnit.SECONDS
)
…
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….
you can try like this
Date date1 = new Date();
SimpleDateFormat formatter1 = new SimpleDateFormat("MMddyyyy");
String format = formatter1.format(date1);
SimpleDateFormat formatter = new SimpleDateFormat("MMddyyyy hh:mm:ss");
Calendar cal = Calendar.getInstance();
Date today = formatter.parse(format+" 00:00:00");
cal.setTime(today);
long start = cal.getTimeInMillis();
System.out.println("start time:"+start);
Date date=formatter.parse(format+" 23:59:59");
cal.setTime(date);
long end = cal.getTimeInMillis();
System.out.println("end time: "+end);
Date tem= new Date();
cal.setTime(tem);
long present = cal.getTimeInMillis();
System.out.println(present);
If you need the start of day, you should set it as such:
Calendar cal = new GregorianCalendar();
cal.clear(Calendar.HOUR); cal.clear(Calendar.AM_PM);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// after all this we'd have the start of day.
// works good if extracted to separate method, which is the unfortunate truth of working with old calendar classes
// minus one milli because Fit API treats includes end of range
long end = cal.getTimeInMillis() - 1;
cal.add(Calendar.MONTH, -1);
long start = cal.getTimeInMillis();
I also may suggest to import and use Joda library for this (prefer Android-specific version).
Using Joda (and java.time package once Java 8 is available on Fit, with minor change), you can write equivalent code like this:
DateTime date = LocalDate.now().toDateTimeAtStartOfDay();
long end = date.getMillis() - 1;
long start = date.minusMonths(1).getMillis();
I have a date string in Utc format -
String dateStr = "2017-03-03T13:14:28.666Z";
And I want to convert it to below format in Java date representation in ZonedDateTime.
When ZonedDateTime is printed it should show
String dateStr = "2017-03-03T00:00:00.000Z";
I have tried following code -
String timeZone = "America/Los_Angeles";
DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZoneId zoneId1 = ZoneId.of(timeZone);
String dateStr = "2017-03-03T13:14:28.666Z";
Instant inst = Instant.parse(dateStr, dtf2);
ZonedDateTime dateTimeInTz = ZonedDateTime.ofInstant(inst, zoneId1);
ZonedDateTime startTime = dateTimeInTz.with(LocalTime.of(0, 0, 0, 0));
ZonedDateTime endTime = dateTimeInTz.with(LocalTime.MAX);
System.out.println("Start:"+startTime+", End:"+endTime);
System.out.println("Start:"+startTime.toString()+", End:"+endTime.toString());
ZonedDateTime nT = ZonedDateTime.of ( LocalDate.parse(dateStr, dtf1) , LocalTime.of (0,0,0,0) , ZoneId.of ( timeZone ) );
System.out.println("Start:"+nT);
Output:
Start:2017-03-03T00:00-08:00[America/Los_Angeles], End:2017-03-03T23:59:59.999999999-08:00[America/Los_Angeles]
Start:2017-03-03T00:00-08:00[America/Los_Angeles], End:2017-03-03T23:59:59.999999999-08:00[America/Los_Angeles]
Start:2017-03-03T00:00-08:00[America/Los_Angeles]
I want the start time to be normalized in ZonedDateTime.
I want to achieve it using java libraries only not any third party library.
tl;dr
You are working too hard.
Instant.parse( "2017-03-03T13:14:28.666Z" )
.truncatedTo( ChronoUnit.DAYS )
.toString()
2017-03-03T00:00.00Z
Details
What does "normalized in ZonedDateTime" mean? Please edit your Question to clarify.
When ZonedDateTime is printed it should show … "2017-03-03T00:00:00.000Z"
What you are asking is a contradiction. A ZonedDateTime has an assigned time zone for when you want to view a moment though the wall-clock time of a particular region. So asking for a ZonedDateTime to generate a string in UTC such as "2017-03-03T00:00:00.000Z" makes no sense. The Z is short for Zulu and means UTC.
Your input string is in standard ISO 8601 format. The java.time classes use these standard formats by default. So no need to specify a formatting pattern, no need for the DateTimeFormatter class.
Parse as an Instant, a point on the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.parse( "2017-03-03T13:14:28.666Z" );
If you want midnight in UTC, truncate.
Instant instantMidnightUtc = instant.truncatedTo( ChronoUnit.DAYS );
instantMidnightUtc.toString(): 2017-03-03T00:00.00Z
No need for the ZonedDateTime class.
If you want to work with a date-only without any time-of-day and without a time zone, use the LocalDate class.
By the way, do not assume the first moment of the day is always 00:00:00. That is true for UTC. But various time zones may have anomalies such as Daylight Saving Time (DST) where the day may start at another time-of-day such as 01:00:00.
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 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 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.
String timeZone = "America/Los_Angeles";
DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
ZoneId zoneId1 = ZoneId.of(timeZone);
String dateStr = "2017-03-03T13:14:28.666Z";
Instant inst = Instant.parse(dateStr, dtf2);
ZonedDateTime dateTimeInTz = ZonedDateTime.ofInstant(inst, zoneId1);
ZonedDateTime startTime = dateTimeInTz.with(LocalTime.of(0, 0, 0, 0));
ZonedDateTime endTime = dateTimeInTz.with(LocalTime.MAX);
String strStart = (startTime.toString().split("T"))[0] + "T00:00:00.000Z";
String strEnd = (endTime.toString().split("T"))[0] + "T00:00:00.000Z";
System.out.println("Start:"+strStart +", End:"+strEnd );
EDIT new method :
TimeZone timeZone = TimeZone.getTimeZone("Europe/Copenhagen");
Calendar cal = Calendar.getInstance(timeZone);
Calendar defaut = new GregorianCalendar( cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),0,0,0);
You juste need to get all your necessary fields. With, for example, a dateFormat.
Hope it will help you
You can simply do:
DateUtils.truncate(yourDate, Calendar.DAY_OF_MONTH);
Hope this will help you
I am trying to calculate the amount of time until the start of a soccer game.
This is what I know:
I have the time of an event:2016-08-16T19:45:00Z
I know the string format of it is "yyyy-M-dd'T'h:m:s'Z'"
I know the timezone is "CET".
I want to be able to calculate the difference from the current time to this date in days.
This is what I have tried:
String gameDate = "2016-03-19T19:45:00'Z'"
DateFormat apiFormat = new SimpleDateFormat("yyyy-M-dd'T'h:m:s'Z'");
apiFormat.setTimeZone(TimeZone.getTimeZone("CET"));
Date dateOfGame = apiFormat.parse(gameDate);
DateFormat currentDateFormat = new SimpleDateFormat("yyyy-M-dd'T'h:m:s'Z'");
currentDateFormat.setTimeZone(TimeZone.getTimeZone(userTimezone));
Date currentDate = apiFormat.parse(currentDateFormat.format(new Date()));
long lGameDate = dateOfGame.getTime();
long lcurrDate = currentDate.getTime();
long difference = lGameDate - lcurrDate;
Date timeDifference = new Date(difference);
String daysAway = new SimpleDateFormat("d").format(timeDifference);
Integer intDaysAway = Integer.parseInt(daysAway);
You are probably wondering why I don't just get the date of the game (8) and subtract the current date (19). I don't do that in the edge case that the current date is the 29th and the game date is the 3rd of the next month.
Nobody has yet provided a Java 8 java.time answer...
String eventStr = "2016-08-16T19:45:00Z";
DateTimeFormatter fmt = DateTimeFormatter.ISO_ZONED_DATE_TIME;
Instant event = fmt.parse(eventStr, Instant::from);
Instant now = Instant.now();
Duration diff = Duration.between(now, event);
long days = diff.toDays();
System.out.println(days);
tl;dr
ChronoUnit.DAYS.between(
Instant.parse( "2016-08-16T19:45:00Z" ).atZone( ZoneId.of( "Europe/Paris" ) ),
Instant.parse( "2016-08-23T12:34:00Z" ).atZone( ZoneId.of( "Europe/Paris" ) )
);
Define “days”
There are two ways to count a number of days. Your Question is not quite clear which you intended. This Answer shows example code for both ways.
Calendar-based days by dateApply the intended time zone to determine the dates of the start and the the stop. A date is determined by zone, as for any given moment the date varies around the globe being “tomorrow” towards the east while “yesterday” to the west depending where you sit. For example a few minutes after midnight in Paris France a new day while still “yesterday” in Montréal Québec.
24-hour chunks of timeIf you consider only generic days of 24-hour chunks of time while ignoring anomalies such as Daylight Saving Time (DST), then you get the total number of seconds between the beginning and ending moment and divide that by 24-hours. In this approach we ignore the calendar and its dates.
Example of the differences: Start late Monday night, an hour before midnight. Stop an hour after midnight on Wednesday morning. For 24-hour chunks that total of 26 hours is a single day. But by calendar dates that would two elapsed days, having touched three calendar days.
Why two days if we touched three? Date-time work commonly uses the Half-Open approach where the beginning is inclusive while the ending is exclusive.
Avoid legacy date-time classes
The modern way to do this work is with the java.time classes rather than the troublesome old legacy date-time classes (Date, Calendar, etc.).
The Answer by dcsohl is correct but could be shorter. No need to be explicit about the DateTimeFormatter as the input string is in one of the standard ISO 8601 formats used by default.
I know the string format of it is "yyyy-M-dd'T'h:m:s'Z'"
As part of the ISO 8601 standard, the Z on the end is short for Zulu and means UTC.
String startInput = "2016-08-16T19:45:00Z" ;
String stopInput = "2016-08-23T12:34:00Z" ;
Parse as Instant objects. 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 start = Instant.parse( startInput );
Instant stop = Instant.parse( stopInput );
I know the timezone is "CET".
Time zone is irrelevant to parsing the strings. But time zone does matter in terms of calculating elapsed days if counting by calendar dates rather than by 24-hours per generic day.
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 or CET as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Europe/Paris" );
Adjust both our start and stop moments into that time zone.
ZonedDateTime zdtStart = start.atZone( z );
ZonedDateTime zdtStop = stop.atZone( z );
The java.time framework provides two classes for spans of time:
Period for years-months-days
Duration for hours-minutes-seconds
The Period class takes a pair of LocalDate objects, date-only values without time-of-day and without time zone. We can extract LocalDate objecs from our ZonedDateTime objects. Remember that date is determined by zone. So it is crucial that we adjusted our UTC values into ZonedDateTime objects.
Period p = Period.between( zdtStart.toLocalDate() , zdtStop.toLocalDate() );
You can interrogate that Period for the number of years and months and days of that span of time.
If you want a total number of days, use the ChronoUnit enum.
long days = ChronoUnit.DAYS.between( zdtStart , zdtStop );
The above is for calendar date-based counting of days.
If you want to count by generic chuncks of 24-hour periods, use the Duration class as shown in the Answer by dcsohl.
Duration.between( start , stop ).toDays()
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, 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.
Try doing/ using TimeUnit:
Example:
final String gameDate = "2016-03-19T19:45:00Z";
final SimpleDateFormat apiFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
apiFormat.setTimeZone(TimeZone.getTimeZone("CET"));
final Date dateOfGame = apiFormat.parse(gameDate);
final long millis = dateOfGame.getTime() - System.currentTimeMillis();
System.out.println(dateOfGame.getTime() - System.currentTimeMillis());
final String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
System.out.println(hms);
This will print the output:
72:57:34
72 hours, 57 minutes and 34 seconds from now until gameDate
You could simply take the result from long difference = lGameDate - lcurrDate;, which is the difference in milliseconds, and convert to whatever unit you like.
For example, in days: int days = difference/1000/3600/24;
This is what you need:
public static void main (String[] args) throws Exception
{
String gameDate = "2016-03-19T19:45:00Z";
DateFormat apiFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
apiFormat.setTimeZone(TimeZone.getTimeZone("CET"));
Date dateOfGame = apiFormat.parse(gameDate);
long now = new Date().getTime() / (3600000 * 24);
long game = dateOfGame.getTime() / (3600000 * 24);
System.out.println(now - game);
}
This will work because you are getting number of full days since epoch for date of game and now and just need to find difference. Other solutions will have errors in border cases.
Your variable difference contains the time difference in milliseconds. To convert those milliseconds to days, hours, minutes, seconds I recommend you to use the java.util.concurrent.TimeUnit class.
Example:
final long durationMinutes = TimeUnit.MILLISECONDS.toMinutes(difference);
final long durationSeconds = TimeUnit.MILLISECONDS.toSeconds(difference)
- TimeUnit.MINUTES.toSeconds(durationMinutes);
final long durationMillis = difference- TimeUnit.MINUTES.toMillis(durationMinutes)
- TimeUnit.SECONDS.toMillis(durationSeconds);
final String durationString = String.format("%d min, %d s, %d ms", durationMinutes, durationSeconds, durationMillis);
First of all your date format is wrong. It should be yyyy-MM-dd'T'HH:mm:ss'Z' instead of yyyy-M-dd'T'h:m:s'Z'.
Also, your gameDate String should end in Z and not 'Z'.
You can easily get the difference in days by just calling the getTime() function on current and given dates. You don't even have to format the current date.
Here is the code snippet:
public static void main (String[] args) throws Exception
{
String gameDate = "2016-03-19T19:45:00Z";
DateFormat apiFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
apiFormat.setTimeZone(TimeZone.getTimeZone("CET"));
Date dateOfGame = apiFormat.parse(gameDate);
long difference = new Date().getTime() - dateOfGame.getTime();
System.out.println((double)difference / (3600000d * 24d));
}
You can do the rounding on the result if you want.
How to display the date, month, and year of a particular month in for loop dynamically in Java?
This demonstrates briefly some of the basics of the SimpleDateFormat and GregorianCalendar classes in Java. It was the best I could do based on your question.
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
public class Main {
public static void main(String[] args) {
int year = 2012;
int month = 4;
/* The format string for how the dates will be printed. */
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
/* Create a calendar for the first of the month. */
GregorianCalendar calendar = new GregorianCalendar(year, month, 1);
/* Loop through the entire month, day by day. */
while (calendar.get(GregorianCalendar.MONTH) == month) {
String dateString = format.format(calendar.getTime());
System.out.println(dateString);
calendar.add(GregorianCalendar.DATE, 1);
}
}
}
Using java.time
The other Answer uses the troublesome old date-time classes, now legacy, supplanted by the java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
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.
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 );
YearMonth
We care about the whole month. So use a YearMonth object to represent that.
YearMonth ym = YearMonth.from( today );
Get the first of the month.
LocalDate localDate = ym.atDay( 1 );
Loop, incrementing the date by one day at a time, until past the end of month. We can test that fact by seeing if each incremented date has the same YearMonth as today. Collect each date in a List.
List<LocalDate> dates = new ArrayList<>( 31 ); // Collect each date. We know 31 is maximum number of days in any month, so set initial capacity.
while( YearMonth.of( localDate).equals( ym ) ) { // While in the same year-month.
dates.add( localDate ); // Collect each incremented `LocalDate`.
System.out.println( localDate );
// Set up next loop.
localDate = localDate.plusDays( 1 );
}
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 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 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.