I'm currently learning how to create applications for Android, but my Java is quite rusty as I'm more of a .NET person.
If in C#, I wanted to create a DateTime object with the value set to todays date plus 5 years, I could use
DateTime dt = DateTime.Now.AddYears(5);
Is there something similar to this in the Java language?
You could use a Calendar to do the calculation:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, 5);
Date date = cal.getTime(); // getTime() returns a Date object
you can use JODA time --- http://joda-time.sourceforge.net to create DateTime object.
Use plusYears method to add 5 years to it -- http://joda-time.sourceforge.net/api-release/org/joda/time/DateTime.html
DateTime.now().plusYears(5);
Related
I need to compare whether a DateTime object is greater/less than 9AM PST using JodaTime library in Android.
I am getting the DateTime object in PST like this:
DateTime dt = new DateTime(DateTimeZone.forID( "America/Los_Angeles" ));
How can I compare whether the time recorded for this object is greater/less than 9AM PST?
Thanks.
You can use one of the next ways to do what you want.
1) Create a DateTime with the TimeZone and the hour that you want.
DateTime dt = new DateTime()
.withHourOfDay(9)
.withZone(DateTimeZone.forID("America/Los_Angeles"));
And then compare dt with the DateTime that you receive, create, etc.
dt.isAfter(date) or dt.isBefore(date)
2) You can set the TimeZone that you want to a copy of the DateTime that you receive.
I say copy because DateTime object is immutable. You can not modify the DateTime which you receive but create one from it, yes. You can read more about that here: Why are Joda objects immutable?
datePST = date.withZone(DateTimeZone.forID("America/Los_Angeles"));
int hour = datePST.getHourOfDay()
Now you just need to check if hour is < or > than 9.
Here is a part from my code:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dateFormat.parse(jahr+"-"+monat+"-"+tag));
And now I want to print out some moving easter holidays in Germany.
gc.add(Calendar.DAY_OF_MONTH, -2);
System.out.println("Karfreitag;"+dateFormat.format(gc.getTime()));
gc.add(Calendar.DAY_OF_MONTH, +3);
System.out.println("Ostermontag;"+dateFormat.format(gc.getTime()));
gc.add(Calendar.DAY_OF_MONTH, +38);
To make it a bit clearer.
Eastersunday was on 16.04.2017 this year.
So the first print out is working fine, 'Karfreitag' is two days before eastersunday. So it was the 14.04.2017.
Moving on to eastermonday throws a problem. Eastermonday is the day after eastersunday. Unfortuanately I have to add +3 days because I overwrote the eastersunday date with the 'Karfreitag' date.
So I want to know if it is possible to make the date from eastersunday fix so that I have to change my 3th line into:
gc.add(Calendar.DAY_OF_MONTH, +1);
It think this could be very easy but I have no clue how to change this in a proper way.
As the add method changes the current calendar instance, one solution is to create another one, using the clone() method:
// clone it before changing it
GregorianCalendar other = (GregorianCalendar) gc.clone();
gc.add(Calendar.DAY_OF_MONTH, -2);
System.out.println("Karfreitag;" + dateFormat.format(gc.getTime()));
other.add(Calendar.DAY_OF_MONTH, 1);
System.out.println("Ostermontag;" + dateFormat.format(other.getTime()));
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java 6 or 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, you'll also need the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
As you're dealing with dates (day/month/year), you can use the LocalDate class. In this new API, classes are immutable, so the methods that add a number of days always create another object:
LocalDate easter = LocalDate.parse("2017-04-16");
// minusDays and plusDays return a new LocalDate, keeping the original unchanged
System.out.println("Karfreitag;" + easter.minusDays(2));
System.out.println("Ostermontag;" + easter.plusDays(1));
The output will be:
Karfreitag;2017-04-14
Ostermontag;2017-04-17
If you have the day, month and year as int values, you can create a LocalDate using the of method:
int tag = 16;
int monat = 4;
int jahr = 2017;
// Easter
LocalDate easter = LocalDate.of(jahr, monat, tag);
Convert from/to GregorianCalendar
If you still need to work with GregorianCalendar, you can easily convert it from/to the new API. In Java 8 there are new methods to do the conversion, while in Java 6/7 ThreeTen Backport there's the org.threeten.bp.DateTimeUtils class:
// Java 8: convert calendar to local date
LocalDate dt = gc.toZonedDateTime().toLocalDate();
// Java 7: convert calendar to local date
LocalDate dt = DateTimeUtils.toZonedDateTime(gc).toLocalDate();
To convert the LocalDate back to GregorianCalendar is a little bit tricky. A LocalDate has only the date fields (day, month and year), while a GregorianCalendar represents a "full date": a date and time in a specific timezone.
So, when converting a LocalDate to a GregorianCalendar, you must make some assumptions about the time (hour, minutes, etc) and the timezone. One example is to set the time to midnight, and use the JVM default timezone:
// Java 8: convert local date to calendar (midnight in JVM default timezone)
GregorianCalendar cal = GregorianCalendar.from(dt.atStartOfDay(ZoneId.systemDefault()));
// Java 7: convert local date to calendar (midnight in JVM default timezone)
GregorianCalendar cal = DateTimeUtils.toGregorianCalendar(dt.atStartOfDay(ZoneId.systemDefault()));
You can also convert to any other time of the day and change the timezone to whatever you want:
// set to 10:30 AM in Berlin timezone
dt.atTime(10, 30).atZone(ZoneId.of("Europe/Berlin"));
Or you can use the ZonedDateTime returned by toZonedDateTime() directly, and extract the LocalDate part when printing:
// convert calendar to ZonedDateTime
ZonedDateTime z = gc.toZonedDateTime();
// print just the LocalDate part
System.out.println("Karfreitag;" + z.minusDays(2).toLocalDate());
System.out.println("Ostermontag;" + z.plusDays(1).toLocalDate());
// get the original calendar back
GregorianCalendar cal = GregorianCalendar.from(z);
This new API has lots of new types and allows you to choose the best for each case.
Start using java.time.LocalDate. It provide a LocalDate.plusDays(long) that return a copy of the instance.
Returns a copy of this LocalDate with the specified number of days added.
Like this :
LocalDate tomorrow = LocalDate.now().plusDays(1);
And you can get an instance using LocalDate.of(int, int, int) like :
LocalDate date = LocalDate.of(year, month, day);
NOTE: This is a shorter version of Hugo's answer, just realise that there were to part in his answer...
You can use DateUtils.addDays like this:
DateUtils.addDays(gc.getDate(), -2).getTime()
It needs a Date object (you can use gc.getDate() for this) and int number of days to add as arguments and also return a Date object without modifying your original gc.
System.out.println("Karfreitag;"+dateFormat.format(DateUtils.addDays(gc.getDate(), -2).getTime()));
System.out.println("Ostermontag;"+dateFormat.format(DateUtils.addDays(gc.getDate(), 3).getTime()));
System.out.println("something else;"+dateFormat.format(DateUtils.addDays(gc.getDate(), 38).getTime()));
In Android its available from API level 3,in Java you'll have to use Apache Commons
While referring to a particular course I came across the following code to retrieve the current day:
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
long dateTime;
dateTime = dayTime.setJulianDay(julianStartDay);
day = getReadableDateString(dateTime);
private String getReadableDateString(long time){
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("E MMM d");
return shortenedDateFormat.format(time);
}
My doubt is why are we using this julian method instead of just directly extracting the day from the Date class object which gives the current date and time.
Is your application related to the Eastern Orthodox religious calendar? As far as I'm aware, that's the only place the Julian calendar is still in use.
The Java Date and Calendar classes use the Gregorian calendar by default. (Calendar.getInstance methods return a GregorianCalendar object unless one of two specific locales is specified.) If your application needs to use the Julian calendar instead, that would explain this implementation.
I am creating Date object in java.
First way:
By using Calender
Date today = Calendar.getInstance().getTime();
Second way:
with Date class
Date today1 = new Date();
Which one is most effective way here?
Since Java 8 you should go for LocalDateTime or LocalDate:
LocalDateTime timePoint = LocalDateTime.now(
); // The current date and time
LocalDate.of(2012, Month.DECEMBER, 12); // from values
LocalDate theDate = timePoint.toLocalDate(); // or
theDate = LocalDate.now(); //
Fromt the documentation:
[For example, the existing classes (such as java.util.Date and
SimpleDateFormatter) aren’t thread-safe, leading to potential
concurrency issues for users—not something the average developer would
expect to deal with when writing date-handling code.
Some of the date and time classes also exhibit quite poor API design.
For example, years in java.util.Date start at 1900, months start at 1,
and days start at 0—not very intuitive.]1
If you have to decide between the two. Take the new Date(). As the Calendar.getInstance().getTime() would create a Calendar instance which you could not use afterwards.
You can use this too!
Date newDate = new GregorianCalendar(year, month, day).getTime();
Within your options, I will prefer the first alternative.
This question already has answers here:
How to check if a date Object equals yesterday?
(9 answers)
Closed 8 years ago.
I have these codes to get the date today in my server
DefaultTableModel dnow = MyDB.DataTable("SELECT date_format(now(),'%m-%d-%Y')");
and these code for the formatting for the date.
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
now how can I get the date of yesterday?
should I just minus it with one?
An alternative approach is to do the math in SQL. The statement may vary depending on what database platform you're using.
DefaultTableModel dnow =
MyDB.DataTable("SELECT date_format(now() - INTERVAL 1 DAY,'%m-%d-%Y')");
No, build a Date (or better yet use joda's DateTime object) and then do your arithmetic. I will give you two solutions, one with Joda and the other without, starting with without:
Date d = format.parse(dnow.getDataVector().get(dnow.getTable().getSelectedRow()));
d.add(Calendar.DATE, -1);
Now, using joda:
DateTime d = new DateTime(format.parse(dnow.getDataVector().get(dnow.getTable().getSelectedRow()))).minusDays(1);
This should work perfect for you,
Calendar cal = Calendar.getInstance()
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date = "+ cal.getTime());
This will simply subtract 1 day from the current calendar date, providing you yesterdays date
If you store your timestamps internally as POSIX times (milliseconds since MN Jan 1, 1970) then you can add or subtract a day to any time stamp as easily as:
Date today = new Date(); // today
Date tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000)); // tomorrow
The huge bonus to POSIX time is that it is always in UTC. UTC is a global, "fixed" point of reference. Then if you need to need to have this date displayed for the user in any time zone, in any daylight savings zone, for any place that is accounted for in the Olson Time Zone database, you can simply create a Calendar:
GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("America/Chicago"));
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setCalendar(gc);
sdf.applyPattern("MM-dd-yyyy");
// Now your formatter is set with the pattern and a time zone-aware Calendar.
// The world is at your command
String myOutput = sdf.format(tomorrow);
I highly recommend dealing with timestamps internally in your data model in some form of UTC representation. Doing date arithmetic with POSIX time (or Julian Day Numbers, or Modified Julian Day Numbers) is easy peasy, and the Java date/time API has enough capability to deal with most local time conversions without much fuss from you.