issue with comparing two dates in joda time API - java

I have a below program to compare two dates.
I get timestamps that are date1 and currentTimestamp, here i need to compare only dates not the time values.But below program always returns -1.(value)
timestamp date1 = "2017-01-20 14:51:30.091" // i get this from service call in this format
SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_TIMESTAMP_FORMAT);
Calendar calendar = Calendar.getInstance();
String formattedDate = dateFormat.format(calendar.getTime());
java.util.Date currentDate = dateFormat.parse(formattedDate);
java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(currentDate.getTime());
int value = DateTimeComparator.getDateOnlyInstance().compare(date1 , currentTimestamp );
How to compare only dates regardless of time. Please help me on this.
UPDATED:
i changed to below code
timestamp date1 = "2017-01-20 14:51:30.091" // i get this from service call in this format
LocalDate localDate = new LocalDate();
int value = DateTimeComparator.getDateOnlyInstance().compare(date1 , localDate );
this gives me error saying "java.lang.IllegalArgumentException: No instant converter found for type: org.joda.time.LocalDate"

This is NOT Joda solution...
Use: Apache library 'commons-lang3-x.x.jar' (DateUtils)
#Test
public void testCompare() {
Date current = new Date();
Date previous = DateUtils.addHours(DateUtils.addDays(new Date(), -1),5);
assertEquals(1,DateUtils.truncatedCompareTo(current,previous,Calendar.DATE));
assertEquals(0,DateUtils.truncatedCompareTo(current,current,Calendar.DATE));
assertEquals(-1,DateUtils.truncatedCompareTo(previous,current,Calendar.DATE));
}

You can Try this code with JodaTime :
DateTime date1 = DateTime.parse("2017-01-20 14:51:30.091", DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS"));
DateTime now = new DateTime();
int value = DateTimeComparator.getDateOnlyInstance().compare(date1 , now);

To compare DateTime in joda without time you have 2 options:
convert DateTime to LocalDate .
Use DateTimeComparator.getDateOnlyInstance
For example:
#Test
public void compareJodaTime() {
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS");
String today = "2017-01-20 14:51:30.091";
String tomorrow = "2017-01-21 14:51:30.091";
DateTime now = DateTime.now();
Assert.assertThat(now.toLocalDate().compareTo(DateTime.parse(today, dateTimeFormatter).toLocalDate()), Matchers.is(0));
Assert.assertThat(now.toLocalDate().compareTo(DateTime.parse(tomorrow, dateTimeFormatter).toLocalDate()), Matchers.is(-1));
Assert.assertThat(now.toLocalDate().isEqual(DateTime.parse(today, dateTimeFormatter).toLocalDate()), Matchers.is(true));
Assert.assertThat(now.toLocalDate().isBefore(DateTime.parse(tomorrow, dateTimeFormatter).toLocalDate()), Matchers.is(true));
Assert.assertThat(DateTimeComparator.getDateOnlyInstance().compare(now, DateTime.parse(today, dateTimeFormatter)), Matchers.is(0));
Assert.assertThat(DateTimeComparator.getDateOnlyInstance().compare(now, DateTime.parse(tomorrow, dateTimeFormatter)), Matchers.is(-1));
}

Related

How to Convert Time Zone to UTC time zone using jorda time

Using this code
String twelveHourTime="06:00 PM";
public static DateTime convert12HourTimeTo24HourTime(String twelveHourTime) {
DateTimeFormatter dateTimeFormatter =
DateTimeFormat.forPattern(AppConstants.TWELVE_HOUR_TIME_FORMAT);
DateTime dateTime = dateTimeFormatter.parseDateTime(twelveHourTime);
return new DateTime().withHourOfDay(dateTime.getHourOfDay())
.withMinuteOfHour(dateTime.getMinuteOfHour());
}
I am getting this date time:
String datetime=2017-09-15T18:00:23.153+05:30
Now I want to convert it to the US time zone.
Please suggest me how to do this.
You can use SimpleDateFormat for conversion
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH24:MI");
Date date = df.parse(datetime);
Use localDateTime:
DateTime dt = new LocalDateTime(timestamp.getTime()).toDateTime(DateTimeZone.UTC);
you can use it by using TimeZone and SimpleDateFormat :-
TimeZone time = TimeZone.getTimeZone("UTC");
Calendar cal = Calendar.getInstance(time);
final Date startDate = cal.getTime();
SimpleDateFormat sdfAmerica = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a");
sdfAmerica.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String sDateInAmerica = sdfAmerica.format(startDate);
edDate.setText(sDateInAmerica);

converting date object with a known timezone, to current timezone

So I'm getting some date objects from a web server, I know that the server has the time in GMT +1 (Berlin), how can I convert the date object, to the current phone timezone date object?
Most of the questions on stackoverflow are only about formatting within a timezone, but not actually converting like this.
I've tried this
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
calendar.setTime(timeFromServer);
Calendar calendar2 = new GregorianCalendar(TimeZone.getDefault());
calendar2.setTimeInMillis(calendar.getTimeInMillis());
WHen I print, calendar2.getTime().toString() and timeFromServer.toString() will be the same;
I used Joda time and it works. You can try with Joda time. This method will convert time from server to display format time below and change to the relevant local time
public static final String SERVER_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DISPLAY_POST_FORMAT = "HH:mm dd/MM/yyyy";
public static String convertDateStrToDisplayFormat(String timeFromServer) {
DateTimeFormatter serverFormatter = DateTimeFormat.forPattern(Constants.SERVER_FORMAT);
serverFormatter.withZone(DateTimeZone.forID("Europe/Berlin"));
DateTime dateTime = DateTime.parse(timeFromServer, serverFormatter);
DateTimeFormatter pointTimeFormatter = DateTimeFormat.forPattern(Constants.POINT_TIME_FORMAT);
pointTimeFormatter.withZone(DateTimeZone.forID("Europe/Berlin"));
return pointTimeFormatter.print(dateTime)
}
I use this to convert the date from the server and convert it to current phone timezone date object
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat deviceFormat = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",Locale.ENGLISH);
deviceFormat.setTimeZone(TimeZone.getDefault());
Date utcDate ;
Date deviceDate ;
utcDate = sourceFormat.parse(event_date);
deviceDate = deviceFormat.parse(utcDate.toString());
event_date is a String that has the server date. After this you have your converted Date on deviceDate.
java.util.Date does not use timezone, so when you try to print the string representation of the following date objects using method Date#toString(), the results are the same:
calendar2.getTime().toString()
timeFromServer.toString()
In order to test the string representation correctly with timezone, you need to use SimpleDateFormat:
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
f.setTimeZone(calendar.getTimeZone());
// Date correctly printed with timezone:
System.out.println(f.parse(calendar.getTime()));
However, your conversion written in the question is correct, here's how I tested it using JUnit:
#Test
public void testDateConversion() throws ParseException {
String serverText = "2017-03-02T11:54:30.207+01:00";
SimpleDateFormat serverFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
serverFmt.setTimeZone(TimeZone.getTimeZone("GMT+1"));
Date timeFromServer = serverFmt.parse(serverText);
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT-1"));
calendar.setTime(timeFromServer);
assertEquals(2017, calendar.get(Calendar.YEAR));
assertEquals(Calendar.MARCH, calendar.get(Calendar.MONTH));
assertEquals(2, calendar.get(Calendar.DAY_OF_MONTH));
assertEquals(9, calendar.get(Calendar.HOUR_OF_DAY));
assertEquals(54, calendar.get(Calendar.MINUTE));
assertEquals(30, calendar.get(Calendar.SECOND));
assertEquals(207, calendar.get(Calendar.MILLISECOND));
SimpleDateFormat currFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
currFmt.setTimeZone(calendar.getTimeZone());
System.out.printf("server_timestamp = %d, server_date = '%s', server_str = '%s'%n",
timeFromServer.getTime(),
serverFmt.format(timeFromServer),
timeFromServer.toString());
System.out.printf("current_timestamp = %d, current_date = '%s', current_str = '%s'%n",
calendar.getTime().getTime(),
currFmt.format(calendar.getTime()),
calendar.getTime().toString());
}
Result:
server_timestamp = 1488452070207, server_date = '2017-03-02T11:54:30.207+01:00', server_str = 'Thu Mar 02 11:54:30 CET 2017'
current_timestamp = 1488452070207, current_date = '2017-03-02T09:54:30.207-01:00', current_str = 'Thu Mar 02 11:54:30 CET 2017'
See also:
SimpleDateFormat (Java Platform SE 7)

How to convert date and time to est format in android?

Here is my code.
public String getDateTime()
{
String dateAndTime =
(new SimpleDateFormat("hh:mm aaa")).format(new Date());
return dateAndTime;
}
public String getDate()
{
android.text.format.DateFormat df = new android.text.format.DateFormat();
String Date = df.format("MM-dd-yyyy", new java.util.Date()).toString();
return Date;
}
I have searched about this. but, i cant find the perfect answer. Please help me.
You can use the below function
private Date shiftTimeZone(Date date, TimeZone sourceTimeZone, TimeZone targetTimeZone) {
Calendar sourceCalendar = Calendar.getInstance();
sourceCalendar.setTime(date);
sourceCalendar.setTimeZone(sourceTimeZone);
Calendar targetCalendar = Calendar.getInstance();
for (int field : new int[] {Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND}) {
targetCalendar.set(field, sourceCalendar.get(field));
}
targetCalendar.setTimeZone(targetTimeZone);
System.out.println("........"+targetCalendar.getTimeZone());
return targetCalendar.getTime();
}
Usage:
Date date= new Date();
SimpleDateFormat sf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sf.format(date);
TimeZone tz = TimeZone.getTimeZone("GMT") OR TimeZone tz = sf.getTimeZone();
TimeZone tz1 = TimeZone.getTimeZone("EST");
Date c= shiftTimeZone( date,tz,tz1);
System.out.println("Format : " + sf.format(c));
Output
sun.util.calendar.ZoneInfo[id="EST",offset=-18000000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Format : 01-05-2013 16:23:57
You can find your answer here :
Date and time conversion to some other Timezone in java
You have to use TimeZone class and Calendar class.
Get current time :
Calendar currentdatetime = Calendar.getInstance();
Just pass your time zone name in TimeZone class like this :
TimeZone.getTimeZone("EST");
Use DateFormater
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Then format your time like this :
formatter.setTimeZone(obj);
and get output like this :
System.out.println("EST Time is : "+ formatter.format(currentdatetime .getTime())

Getting ISO8601 from JodaTime with milliseconds

I want to convert my date "2013-03-04T23:00:00" to "yyyy-MM-dd'T'HH:mm:ss.SSSZ" but I keep getting "2013-03-04'T'23:00:00.000+0000". Any help?
item.getEnd() is a XMLGregorianCalendar by the way.
Calendar calendar = item.getEnd().toGregorianCalendar();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = calendar.getTime();
DateTime iso8601 = new DateTime(calendar);
iso8601.toString("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
You should just be able to use the ISODateTimeFormat class that is built in to JodaTime. The example in the documentation is:
DateTime dt = new DateTime();
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
String str = fmt.print(dt);

How to subtract X day from a Date object in Java?

I want to do something like:
Date date = new Date(); // current date
date = date - 300; // substract 300 days from current date and I want to use this "date"
How to do it?
Java 8 and later
With Java 8's date time API change, Use LocalDate
LocalDate date = LocalDate.now().minusDays(300);
Similarly you can have
LocalDate date = someLocalDateInstance.minusDays(300);
Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
Java 7 and earlier
Use Calendar's add() method
Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();
#JigarJoshi it's the good answer, and of course also #Tim recommendation to use .joda-time.
I only want to add more possibilities to subtract days from a java.util.Date.
Apache-commons
One possibility is to use apache-commons-lang. You can do it using DateUtils as follows:
Date dateBefore30Days = DateUtils.addDays(new Date(),-30);
Of course add the commons-lang dependency to do only date subtract it's probably not a good options, however if you're already using commons-lang it's a good choice. There is also convenient methods to addYears,addMonths,addWeeks and so on, take a look at the api here.
Java 8
Another possibility is to take advantage of new LocalDate from Java 8 using minusDays(long days) method:
LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);
Simply use this to get date before 300 days, replace 300 with your days:
Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();
Here,
DateTime is org.joda.time.DateTime;
Date is java.util.Date
Java 8 Time API:
Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);
As you can see HERE there is a lot of manipulation you can do. Here an example showing what you could do!
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
//Add one day to current date.
cal.add(Calendar.DATE, 1);
System.out.println(dateFormat.format(cal.getTime()));
//Substract one day to current date.
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));
/* Can be Calendar.DATE or
* Calendar.MONTH, Calendar.YEAR, Calendar.HOUR, Calendar.SECOND
*/
With Java 8 it's really simple now:
LocalDate date = LocalDate.now().minusDays(300);
A great guide to the new api can be found here.
In Java 8 you can do this:
Instant inst = Instant.parse("2018-12-30T19:34:50.63Z");
// subtract 10 Days to Instant
Instant value = inst.minus(Period.ofDays(10));
// print result
System.out.println("Instant after subtracting Days: " + value);
I have created a function to make the task easier.
For 7 days after dateString: dateCalculate(dateString,"yyyy-MM-dd",7);
To get 7 days upto dateString: dateCalculate(dateString,"yyyy-MM-dd",-7);
public static String dateCalculate(String dateString, String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
try {
cal.setTime(s.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
}
cal.add(Calendar.DATE, days);
return s.format(cal.getTime());
}
You may also be able to use the Duration class. E.g.
Date currentDate = new Date();
Date oneDayFromCurrentDate = new Date(currentDate.getTime() - Duration.ofDays(1).toMillis());
You can easily subtract with calendar with SimpleDateFormat
public static String subtractDate(String time,int subtractDay) throws ParseException {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
cal.setTime(sdf.parse(time));
cal.add(Calendar.DATE,-subtractDay);
String wantedDate = sdf.format(cal.getTime());
Log.d("tag",wantedDate);
return wantedDate;
}

Categories