How to compare one month-with-day to another in Java? - java

I want to compare two date one is to take as current date and another one is static date that is from local variable. I want to compare date and month only i have written one program can anyone confirm is it right or not ?
String str="27/09";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM");
LocalDateTime now = LocalDateTime.now();
String date1=dtf.format(now);
System.out.println("fist date Date 1\t"+date1);
SimpleDateFormat sdformat = new SimpleDateFormat("dd/MM");
Date d1 = sdformat.parse(str);
String date2=sdformat.format(d1);
System.out.println("second date Date2 \t"+date2);
int result = date1.compareTo(date2);
if (result < 0) {
System.out.println("Date1 is before Date2");
}```
LOCALDATE>STATICVARIABLE DATE this is condition and want to compare date and month only.

tl;dr
MonthDay
.of( Month.OCTOBER , 1 )
.isAfter(
MonthDay
.parse(
"27/09" ,
DateTimeFormatter.ofPattern( "dd/MM" )
)
)
Run this code at Ideone.com.
true
java.time.MonthDay
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
For a day of month, use MonthDay class.
MonthDay md = MonthDay.of( 9 , 27 ) ;
For exchanging date-time values as text, ask the publisher of your data to use only standard ISO 8601 formats. For month-day, that format is --MM-DD.
String output = md.toString() ;
--09-27
If you must accept non-standard input, define a formatting pattern with DateTimeFormatter class.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM" ) ;
Parse your input.
String input = "27/09" ;
MonthDay sept27 = MonthDay.parse( input , f ) ;
sept27.toString(): --09-27
See this code run live at Ideone.com.
You can compare MonthDay objects by using their methods isBefore, equals, and isAfter.
If you want the current year-month, you need to a time zone. For any given moment, the date varies around the globe by time zone. So near the start/end of a month, it might be “next” month in Tokyo Japan while simultaneously “previous” month in Toledo Ohio US.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
MonthDay currentYearMonth = MonthDay.now( z ) ;

Related

I can't do math with calendar method in Java, but got the "java: bad operand types for binary operator '-'" error

I'm trying to make a code that tells me how many days left for me to go college, but I am not able to do it with the current date. I can easily make it by setting a date, but I want the current date, so I have to use the calendar method, but can't do math using it.
My code:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar calendar = Calendar.getInstance();
Date start = sdf.parse("10/06/2022");
System.out.println(start - calendar.getTime());
tl;dr
ChronoUnit.DAYS.between(
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) ,
LocalDate.parse( "10/06/2022" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) )
)
Details
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Never use Date/Calendar.
Also, you are attempting to use a date-time class representing a date with time-of-day as seen in UTC (offset of zero) to hold a date-only value. Square peg, round hole.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
LocalDate graduationDate = LocalDate.parse( "10/06/2022" , f ) ;
Determine today's date. That requires a time zone. For any given moment, the date varies around the globe by time zone.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ; // Or ZoneId.systemDefault()
LocalDate today = LocalDate.now( z ) ;
Calculate elapsed time using java.time.temporal.ChronoUnit.
long days = ChronoUnit.DAYS.between( today , graduationDate ) ;
See this code run live at IdeOne.com.
graduationDate: 2022-06-10
today: 2022-03-05
days: 97
Tip: Learn about the ISO 8601 standard for exchanging date-time values as text.
Calendar calendar = Calendar.getInstance();
Calendar collegeDate = Calendar.getInstance();
collegeDate.set(Calendar.DATE,10);
collegeDate.set(Calendar.MONTH, 5);
collegeDate.set(Calendar.YEAR, 2022);
System.out.println(Duration.between(calendar.toInstant(), collegeDate.toInstant()).toDays());
You can try this
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar calendar = Calendar.getInstance();
Date start = sdf.parse("10/06/2022");
long dif = Math.abs(calendar.getTimeInMillis() - start.getTime());
long result = TimeUnit.DAYS.convert(dif, TimeUnit.MILLISECONDS);
System.out.println(result);

Way to get end points of a time interval based on a date?

I think I can do this on my own but I don't want to reinvent a wheel (especially regarding date arithmetic) if I don't have to.
I'm making a swing application that has a drop down where a user can select a time interval with the options being All, Today, This Week, This Month, This Quarter, This Year, Last Week, Last Month, Last Quarter, Last Year. When a user selects one of these I want to calculate the interval.
For instance, today is 1/19/2022. If someone selected This Week, my startDate would be 2022-01-16 00:00:00 and my endDate would be 2022-01-22 11:59:59 (or perhaps it would make more sense to be 2022-01-23 00:00:00?)
For the All Selection I've already implented a method where my startDate is January 1, 1970 and my endDate is a few years into the future from the current time. I also was able to do Today by myself by just getting todays date and adjusting the times from midnight to midnight.
But for all these other options I don't know if there's already a library or such that has calculated them that I could leverage. It's been a while since I touched java in general and don't know the ecosystem well.
Also important to this is that the endDate and startDates are either java.util.Date type or a sublclass of it as I need to integrate it with code that is counting on that.
Any pointers would be greatly appreciated.
I would use java.time.LocalDate, which you can easily obtain from java.util.Date and convert back and forth if needed.
Here is how you can get the start of the current week using LocalDate (using the US locale, you can use something else if the start of the week is different)
LocalDate now = LocalDate.now();
TemporalField fieldUS = WeekFields.of(Locale.US).dayOfWeek();
System.out.println(now.with(fieldUS, 1));
You can find how to do the rest of your requirements from other StackOverflow posts with a little searching.
Here is how you can convert a Date to LocalDate
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
And convert from LocalDate to Date
LocalDate localDate = LocalDate.now();
Date date = Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
Time zone
You said:
For instance, today is 1/19/2022. If someone selected This Week, my startDate would be 2022-01-16 00:00:00
Be aware that determining a moment requires a time zone. The time 00:00 on the 16th happened several hours earlier in Tokyo Japan than in Toledo Ohio US.
Also, some dates in some time zones, the day does not begin at 00:00. Rather than assume, let java.time determine the first moment of the day.
ZoneId zTokyo = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime todayStartTokyo = ZonedDateTime.now( zTokyo ).toLocalDate().atStartOfDay( zTokyo ) ;
Months
For a month, use java.time.YearMonth.
ZoneId zAuckland = ZoneId.of( "Pacific/Auckland" ) ;
LocalDate ld = LocalDate.of( 2022 , 1 , 19 ) ;
YearMonth ym = YearMonth.from( ld ) ;
Determine date range.
LocalDate dateStart = yw.atDay( 1 ) ;
LocalDate dateEnd = yw.plusMonths( 1 ) ;
Determine moments.
ZonedDateTime zdtStart = dateStart.atStartOfDay( zAuckland ) ;
ZonedDateTime zdtEnd = dateEnd.atStartOfDay( zAuckland ) ;
Quarters
If your definition of quarters agrees with that of ISO 8601, I suggest adding the ThreeTen-Extra library to your project for its org.threeten.extra.Quarter enum and org.threeten.extra.YearQuarter class.
Again, the definition of week used in that class conforms with ISO 8601. If your definition differs, this class will not work for you. An ISO 8601 week starts on Monday, and runs through Sunday, with week # 1 of the year having the first Thursday of the calendar year, for a resulting 52 or 53 full-seven-day weeks per week-based-year.
LocalDate ld = LocalDate.of( 2022 , 1 , 19 ) ;
YearQuarter yq = YearQuarter.from( localDate ) ;
LocalDate yqStart = yq.atDay( 1 ) ;
LocalDate yqEnd = yq.plusQuarters( 1 ).atDay( 1 ) ;
Same range in moments:
ZoneId zTunis = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdtStart = yqStart.atStartOfDay( zTunis ) ;
ZonedDateTime zdtEnd = yqEnd.atStartOfDay( zTunis ) ;
Weeks
As with quarters, for working with weeks I suggest adding the ThreeTen-Extra library for its org.threeten.extra.YearWeek class. The built-in java.time do have some week features, but they are limited.
ZoneId zEdmonton = ZoneId.of( "America/Edmonton" ) ;
LocalDate todayEdmonton = LocalDate.now( zEdmonton ) ;
YearWeek yw = YearWeek.from( todayEdmonton ) ;
Or, just:
YearWeek yw = YearWeek.now( zEdmonton ) ;
To determine date range:
LocalDate weekStart = yw.atDay( DayOfWeek.MONDAY ) ;
LocalDate weekEnd = yw.plusWeeks( 1 ).atDay( DayOfWeek.MONDAY ) ;
To determine a range of moments, use same code seen above, calling atStartOfDay.

Convert timestamp to Date time for a particular timezone

I want to convert a timestamp (which is in GMT) to a local date and time.
This is what I have implemented so far, but it is giving me wrong month
Timestamp stp = new Timestamp(1640812878000L);
Calendar convertTimestamp = convertTimeStamp(stp,"America/Phoenix");
System.out.println(convertTimestamp.getTime());
public static Calendar convertTimeStamp( Timestamp p_gmtTime, String p_timeZone) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy HH:MM:SS a", Locale.ENGLISH);
DateFormat formatter = DateFormat.getDateTimeInstance();
if (p_timeZone != null) {
formatter.setTimeZone(TimeZone.getTimeZone(p_timeZone));
} else {
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
}
String gmt_time = formatter.format(p_gmtTime);
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(gmt_time));
return cal;
}
Any help would be appreciated.
You cannot convert a timestamp to another timezone, cause timestamps are always GMT, they are a given moment in the line of time in the universe.
We humans are used to local time on our planet, so a timestamp can be formatted to be more human readable, and in that context it is converted to a local timezone.
Using legacy java.util.* packages, this is done as follows:
DateFormat tzFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
tzFormat.setTimeZone(TimeZone.getTimeZone("CET")); // Use whatever timezone
System.out.println(tzFormat.format(date));
If you need to make "math" over the timestamp on local timezone (like, tomorrow at 8:00 local timezone), then the situation is more complex.
To do this you can resort to a number of hacks (like parsing or modifying the string obtained with the method above), or use the new Java date & time classes that have a specific class to deal with date and time in local time zones:
Instant timestamp = Instant.ofEpochMilli(inputValue);
ZonedDateTime romeTime = timestamp.atZone(ZoneId.of("Europe/Rome"));
Note how this second example uses "Europe/Rome" and not generically "CET". This is very important if you're planning to deal with timezones where DST is used, cause the DST change day (or if they use DST or not) may change from country to country even if they are in the same timezone.
tl;dr
Instant
.ofEpochMilli( // Parse a count of milliseconds since 1970-01-01T00:00Z.
1_640_812_878_000L
) // Returns a `Instant` object.
.atZone( // Adjust from UTC to a time zone. Same moment, same point on the timeline, different wall-clock time.
ZoneId.of( "America/Phoenix" )
) // Returns a `ZonedDateTime` object.
.format( // Generat text representing the date-time value kept within that `ZonedDateTime` object.
DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.MEDIUM )
.withLocale( Locale.US )
) // Returns a `String` object.
See this code run live at IdeOne.com.
Dec 29, 2021, 2:21:18 PM
Details
You are using terrible old date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Never use Timestamp, Calendar, Date, SimpleDateFormat, etc.
Use the Instant class to represent a moment as seen in UTC, with an offset of zero hours-minutes-seconds.
long millisecondsSinceBeginningOf1970InUtc = 1_640_812_878_000L ;
Instant instant = Instant.ofEpochMilli( millisecondsSinceBeginningOf1970InUtc ) ;
Specify the time zone in which you are interested.
ZoneID z = ZoneId.of( "Africa/Tunis" ) ;
Adjust from offset of zero to that time zone to produce a ZonedDateTime object.
ZonedDateTime zdt = instant.atZone( z ) ;
Generate text representing that moment by automatically localizing. Use a Locale to specify the human language to use in translation as well as a culture to use in deciding abbreviation, capitalization, order of elements, and so on.
Locale locale = Locale.JAPAN ; // Or Locale.US, Locale.ITALY, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.LONG ).withLocale( locale ) ;
String output = zdt.format( f ) ;
All of this has been addressed many times on Stack Overflow. Search to learn more.

Convert linux timestamp to android date

I must convert a linux timestamp to android date.
i get this number from server
1386889262
I have written a small code snippet.
Date d = new Date(jsonProductData.getLong(MTIME));
SimpleDateFormat f = new SimpleDateFormat("dd.MM.yyyy");
.setTimeZone(TimeZone.getTimeZone("GMT"));
formatTime = f.format(d);
but it doesen't convert right, this is my result
17.01.1970
EDIT:
Normally i must get this here
12.12.2013
Is there an another method to get the right date???
if your UNIX time stamp is of 10 digit then it does not include milliseconds so do this first 1386889262*1000
and if its 13 digit then it includes milliseconds also then you do not have to multiply unix timestamp with 1000.
In Kotlin we can use this function:
val unix=1386889262*1000 /*if time stamp is of 10 digit*/
val dateFormat = SimpleDateFormat("dd-MM-yy HH:mm:ss");
val dt = Date(unix);
textview.settext(dateFormat.format(dt))
UNIX timestamp should be in milliseconds so multiply the Long value by 1000. So your value 1386889262 would be 1386889262000:
tl;dr
Instant.ofEpochSecond( 1386889262L )
.atZone( ZoneId.of( "Pacific/Auckland" ) )
.toLocalDate()
.toString()
java.time
You appear to have a count of whole seconds from the epoch reference date of first moment of 1970 in UTC, 1970-01-01T00:00:00Z.
The modern approach uses the java.time classes that supplant the troublesome old date-time classes bundled with the earliest versions of Java. For older Android see the ThreeTen-Backport and ThreeTenABP projects.
An Instant represents a point on the timeline in UTC with a resolution of nanoseconds (up to nine digits of decimal fraction).
Instant instant = Instant.ofEpochSecond( 1386889262L ) ;
To generate a String representing this moment, call toString.
String output = instant.toString() ;
Determining a date requires a time zone. For any given moment, the date varies around the globe by zone. Assign a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Extract a date-only value for your purposes.
LocalDate ld = zdt.toLocalDate() ;
Generate a String.
String output = ld.toString() ;
For other formats in your String, search Stack Overflow for DateTimeFormatter.
Your timestamp or epoch time seems in sec "1386889262". You have to do something like this:
long date1 = 1386889262*1000;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm");
Date dt = new Date(date1);
datedisplay.setText(dateFormat.format(dt));
You can also get timestamp in java via
new Date().getTime() ;
It returns a long value.

Calculate diff. between two times given that we have two different strings for time and date

I have time data split in two strings - one string for date, and one for time.
I want to calculate the diff. of such two times in Java.
e.g.
time 1:"26/02/2011" and "11:00 AM"
time 2:"27/02/2011" and "12:15 AM"
Difference would be like 13 hours 15 minutes.
String str_date1 = "26/02/2011";
String str_time1 = "11:00 AM";
String str_date2 = "27/02/2011";
String str_time2 = "12:15 AM" ;
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
Date date1 = formatter.parse(str_date1 + " " + str_time1);
Date date2 = formatter.parse(str_date2 + " " + str_time2);
// Get msec from each, and subtract.
long diff = date2.getTime() - date1.getTime();
System.out.println("Difference In Days: " + (diff / (1000 * 60 * 60 * 24)));
Obs: This is only valid as an aproximation. See Losing Time on the Garden Path.)
try {
String date1 = "26/02/2011";
String time1 = "11:00 AM";
String date2 = "27/02/2011";
String time2 = "12:15 AM";
String format = "dd/MM/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(date1 + " " + time1);
Date dateObj2 = sdf.parse(date2 + " " + time2);
System.out.println(dateObj1);
System.out.println(dateObj2);
long diff = dateObj2.getTime() - dateObj1.getTime();
double diffInHours = diff / ((double) 1000 * 60 * 60);
System.out.println(diffInHours);
System.out.println("Hours " + (int)diffInHours);
System.out.println("Minutes " + (diffInHours - (int)diffInHours)*60 );
} catch (ParseException e) {
e.printStackTrace();
}
output
Sat Feb 26 11:00:00 EST 2011
Sun Feb 27 00:15:00 EST 2011
13.25
Hours 13
Minutes 15.0
You need to first convert the strings to java.util.Date objects (using SimpleDateFormat.parse(String) for instance). Then you can use Date.getTime() for each of the two Date instances that you parsed and compute the difference in milliseconds or make use of a java.util.Calendar or the joda time API for advanced computations.
Have a look at DateFormat, you can use it to parse your strings with the parse(String source) method and the you can easily manipulate the two Dates object to obtain what you want.
DateFormat df = DateFormat.getInstance();
Date date1 = df.parse(string1);
Date date2 = df.parse(string2);
long difference = date1.getTime() - date2.getTime();
Date myDate = new Date(difference);
The to show the Date :
String diff = df.format(myDate);
tl;dr
Duration.between(
ZonedDateTime.of(
LocalDate.parse( "26/02/2011" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ,
LocalTime.parse( "11:00 AM" , DateTimeFormatter.ofPattern( "hh:mm a" ) ) ,
ZoneId.of( "America/Montreal" )
)
,
ZonedDateTime.of(
LocalDate.parse( "27/02/2011" , DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ) ,
LocalTime.parse( "12:15 AM" , DateTimeFormatter.ofPattern( "hh:mm a" ) ) ,
ZoneId.of( "America/Montreal" )
)
).toString()
See live code in IdeOne.com.
Time zone
The Question and the other Answers all ignore the crucial issue of time zone. You cannot calculate elapsed time between two date-time strings without knowing the intended time zone. For example, in places with Daylight Saving Time (DST), on the night of the cut-over, a day may be 23 hours long or 25 hours long rather than 24 hours long.
java.time
The modern way to do date-time work is with the java.time classes. These supplant the troublesome old date-time classes such as java.util.Date and java.util.Calendar.
Local…
First parse the input strings. These lack any indication of time zone, so we parse them as Local… types.
Define a DateTimeFormatter to match your string inputs. By the way, in the future, use standard ISO 8601 formats when serializing date-time values to text.
DateTimeFormatter df = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "26/02/2011" , df ) ;
ld.toString(): 2011-02-2011
DateTimeFormatter tf = DateTimeFormatter.ofPattern( "hh:mm a" );
LocalTime lt = LocalTime.parse( "11:00 AM" , tf ) ;
lt.toString(): 11:00:00
ZoneId
You need to know the time zone intended by your business scenario. I will arbitrarily choose one.
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" );
ZonedDateTime
Apply the zone to get a ZonedDateTime.
ZonedDateTime zdtStart = ZonedDateTime.of( ld , lt , z );
zdtStart.toString(): 2011-02-26T11:00:00-05:00[America/Montreal]
Duration
Do the same to get a zdtStop. Calculate the elapsed time as a span of time not attached to the timeline, in a Duration.
Duration d = Duration.between( zdtStart , zdtStop );
Call toString to generate a String in standard ISO 8601 format for durations: PnYnMnDTnHnMnS. The P marks the beginning while the T separates the two portions.
String output = d.toString();
d.toString(): PT13H15M
In Java 9 and later, call the to…Part methods to access each component.
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….
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 this one
you can calculate days,hours and minutes
public class TimeUtils {
public static final String HOURS = "hours";
public static final String MINUTES = "minutes";
public static final String DAYS = "days";
public static int findTheNumberBetween(String type, Date day1, Date day2) {
long diff = day2.getTime() - day1.getTime();
switch (type) {
case DAYS:
return (int) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
case HOURS:
return (int) TimeUnit.HOURS.convert(diff, TimeUnit.MILLISECONDS);
case MINUTES:
return (int) TimeUnit.MINUTES.convert(diff, TimeUnit.MILLISECONDS);
}
return 0;
}
}
and the use it like
Date day1= TimeUtils.getDateTime("2016-12-08 02:06:14");
Date day2 = TimeUtils.getDateTime("2016-12-08 02:10:14");
Log.d(TAG, "The difference: "+TimeUtils.findTheNumberBetween(TimeUtils.MINUTES,day1,day2));

Categories