I'm trying to create number of Evenement instances and set the date for them:
for (int i=2004; i<2009; i++){
evenementen.add(new Evenement("Rock Werchter", "Rock", "Werchter", 200000,
(Date)formatter.parse(i+"/07/03")));
But I can't seem to get it to work,
Any ideas?
You may want to use Calendar to create your dates.
for (int i=2004; i<2009; i++) {
Calendar cal = Calendar.getInstance();
cal.clear();
// Calendar.JULY may be different depending on the JDK language
cal.set(i, Calendar.JULY, 3); // Alternatively, cal.set(i, 6, 3);
evenementen.add(new Evenement("Rock Werchter", "Rock", "Werchter", 200000,
cal.getTime()));
}
Note that the months are zero-based, so July is 6.
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern API:
import java.time.LocalDate;
import java.time.Month;
public class Main {
public static void main(String[] args) {
for (int i = 2004; i < 2009; i++) {
System.out.println(LocalDate.of(i, Month.JULY, 3));
}
}
}
If you want to do it by parsing the string (the way you have posted in the question), use DateTimeFormatter.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u/M/d", Locale.ENGLISH);
for (int i = 2004; i < 2009; i++) {
LocalDate date = LocalDate.parse(i + "/07/03", dtf);
System.out.println(date);
}
}
}
Output:
2004-07-03
2005-07-03
2006-07-03
2007-07-03
2008-07-03
Learn more about java.time, the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Beware of the locale used for the date formatter (default can be Locale.ENGLISH is your OS is set that way, meaning the year is at the end, not at the beginning of the string)
You need to be sure to have a formatter build as (at the time of writing, 2008, Java6, as in this answer):
formatter = new SimpleDateFormat("yyyy/MM/DD");
Related
My requirement is to compare a given date in a particular format in a given timezone to the current date in the same time zone.
Also while comparing I have to ignore the timezone.
And the comparison result should be:
0 or 1 or -1
One way I have tried is
Set the required timezone
Get the current date using "new Date()" format it using "yyyy-MM-dd" and then parse it again to get the date object
Use the same formatter for supplied date string to be compared
Then compare both dates using compareTo which gives the desired result
public void compareDate(){
TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
Date todayDate = dateFormatter.parse(dateFormatter.format(new Date()));
Date date = dateFormatter.parse("2021-02-28");
System.out.println(todayDate.compareTo(date));
}
But the above looks inefficient to me.
Other way could be to get both the dates like below and then compare?
public static Date getDateWithoutTimeUsingCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
Can someone please suggest a better alternative?
Just one thing, timezone and comparing without time has to be there.
The java.util date-time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.*
Demo using java.time API (modern date-time API):
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Tests
try {
System.out.println(compareWith("2021-02-28", "yyyy-MM-dd", "Asia/Calcutta"));
System.out.println(compareWith("2021/03/03", "yyyy/MM/dd", "Asia/Calcutta"));
} catch (DateTimeException e) {
System.out.println("Date string parsing error occured.");
}
}
static int compareWith(String strDate, String format, String timezone) throws DateTimeException {
ZoneId zoneId = ZoneId.of(timezone);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format, Locale.ENGLISH);
ZonedDateTime today = ZonedDateTime.now(zoneId).with(LocalTime.MIDNIGHT);
ZonedDateTime date = LocalDate.parse(strDate, dtf).atStartOfDay(zoneId);
return today.compareTo(date);
}
}
Output:
1
-1
Learn more about the modern date-time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
I want to get the day of week from the Java Date object when I have an array of Date in String with me.
SimpleDateFormat sourceDateformat = new SimpleDateFormat("yyyy-MM-dd");
public String[] temp_date;
public Int[] day = new Int[5];
Date[] d1= new Date[5];
Calendar[] cal= new Calendar[5]
try {
d1[i]= sourceDateformat.parse(temp_date[i].toString());
cal[i].setTime(d1[i]); // its not compiling this line..showing error on this line
day[i]= cal[i].get(Calendar.DAY_OF_WEEK);
}
catch (ParseException e) {
e.printStackTrace();
}
Does anyone know the answer to this?
You can get the day-integer like that:
Calendar c = Calendar.getInstance();
c.setTime(yourdate); // yourdate is an object of type Date
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); // this will for example return 3 for tuesday
If you need the output to be "Tue" rather than 3, instead of going through a calendar, just reformat the string: new SimpleDateFormat("EE").format(date) (EE meaning "day of week, short version")
Taken from here: How to determine day of week by passing specific date?
// kotlin
val calendar = Calendar.getInstance()
val dateInfo = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.time)
data.text = dateInfo
java.time
You can do it using DateTimeFormatter.ofPattern("EEEE"):
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
// Test
System.out.println(getWeekDayName("2021-04-30"));
}
public static String getWeekDayName(String s) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d", Locale.ENGLISH);
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("EEEE", Locale.ENGLISH);
return LocalDate.parse(s, dtfInput).format(dtfOutput);
}
}
Output:
Friday
Alternatively, you can get it using LocalDate#getDayOfWeek:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
// Test
System.out.println(getWeekDayName("2021-04-30"));
}
public static String getWeekDayName(String s) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d", Locale.ENGLISH);
return LocalDate.parse(s, dtfInput).getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH);
}
}
Output:
Friday
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
This is one of the many things that have become a lot easier with the advent of java.time, the modern Java date and time API.
String tempDate = "2020-03-29";
LocalDate date = LocalDate.parse(tempDate);
DayOfWeek day = date.getDayOfWeek();
System.out.println(day);
Output:
SUNDAY
Of course we now have got an enum for the days of the week. There’s no longer any reason to fiddle with integers and having to remember on what day of week they begin and whether the days are numbered from 0 or 1.
I am expoiting the fact that your expected input format (yyyy-MM-dd in your code) is ISO 8601, the default for java.time, so we don’t need to specify any formatter explicitly.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601
In Kotlin, just do this:
val yourDateStr = "2021-01-01"
val df = DateFormat.parse(yourDateStr)
val weedDay = df.getWeekDay(yourTimeZone)
the below code works, depending on what number you enter in the DAY_OF_WEEK, that returns the specific weekday, in this example it always returns a future date and day will always be Tuesday.
DAY_OF_WEEK
public static String getTodaysDateAndTime(){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 5);
cal.add(Calendar.DAY_OF_WEEK, 2);
Date date = cal.getTime();
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String futureDate = dateformat.format(date);
System.out.println(futureDate);
return futureDate;
}
there are two string
String date = "9/13/2012";
String time = "5:48pm";
the time is GMT+0, I wanna change it to GMT+8,what is the simplest way to change a time to particular timezone
Parse it using a SimpleDateFormat set to the UTC time zone
Format the parsed Date value using a SimpleDateFormat set to the time zone you're interested in. (It's likely to be something other than just "UTC+8" - you should find out which TZDB time zone ID you really want.
For example:
SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy h:mma", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC");
Date date = inputFormat.parse(date + " " + time);
// Or whatever format you want...
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US);
outputFormat.setTimeZone(targetTimeZone);
String outputText = outputFormat.format(date);
(If you can use Joda Time instead, that'd be great - but I understand that it's pretty big for an Android app.)
The Joda-Time library provides a good set of objects for working with dates/times in multiple time zones. http://joda-time.sourceforge.net/
Something like this for example:
String date = "9/13/2012";
String time = "5:48pm";
String[] dateParts = date.split("/");
Integer month = Integer.parseInt(dateParts[0]);
Integer day = Integer.parseInt(dateParts[1]);
Integer year = Integer.parseInt(dateParts[2]);
String[] timeParts = time.split(":");
Integer hour = Integer.parseInt(timeParts[0]);
Integer minutes = Integer.parseInt(timeParts[1].substring(0,timeParts[1].lastIndexOf("p")));
DateTime dateTime = new DateTime(year, month, day, hour, minutes, DateTimeZone.forID("Etc/GMT"));
dateTime.withZone(DateTimeZone.forID("Etc/GMT+8"));
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String date = "9/13/2012";
String time = "5:48pm";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/u h:ma", Locale.UK);
LocalDateTime ldtSource = LocalDateTime.parse(date + " " + time, dtf);
OffsetDateTime odtSource = ldtSource.atOffset(ZoneOffset.UTC);
OffsetDateTime odtTarget = odtSource.withOffsetSameInstant(ZoneOffset.of("+08:00"));
System.out.println(odtTarget);
// In a custom format
System.out.println(odtTarget.format(dtf));
}
}
Output:
2012-09-14T01:48+08:00
9/14/2012 1:48am
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
I am using Joda time api in a Spring 3.0 project for the very first time. Now I have a start and end date and I want to get the date for all mondays between these two dates. How can I do this ?
I have no idea where to start, can someone please advise. I looked at theis post Joda Time: How to get dates of weekdays on some date interval? and it offered some sort of guidance but its still somewhat vague due to little experience with joda.
LocalDate startDate = new LocalDate(2011, 11, 8);
LocalDate endDate = new LocalDate(2012, 5, 1);
LocalDate thisMonday = startDate.withDayOfWeek(DateTimeConstants.MONDAY);
if (startDate.isAfter(thisMonday)) {
startDate = thisMonday.plusWeeks(1); // start on next monday
} else {
startDate = thisMonday; // start on this monday
}
while (startDate.isBefore(endDate)) {
System.out.println(startDate);
startDate = startDate.plusWeeks(1);
}
I recently developed Lamma which is designed to solve this exact use case:
Dates.from(2011, 11, 8).to(2011, 12, 30).byWeek().on(DayOfWeek.MONDAY).build();
and you will get a List<Date> of:
Date(2011,11,14)
Date(2011,11,21)
Date(2011,11,28)
Date(2011,12,5)
Date(2011,12,12)
Date(2011,12,19)
Date(2011,12,26)
FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
Using java.time
The LocalDate class is java.time is akin to the Joda-Time LocalDate. A date-only value, without time-of-day and without time zone. One difference is that java.time eschews constructors for factory methods.
LocalDate start = LocalDate.of( 2011 , 11 , 8 );
LocalDate stop = LocalDate.of( 2012 , 5 , 1 );
Collect the Mondays.
List<LocalDate> mondays = new ArrayList<>();
The TemporalAdjuster interface provides for classes that manipulate date-time values. The TemporalAdjusters class (note the plural name) provides various implementations. We want the nextOrSame and next adjusters, passing the desired DayOfWeek.MONDAY enum object.
LocalDate monday = start.with( TemporalAdjusters.nextOrSame( DayOfWeek.MONDAY ) );
while( monday.isBefore( stop ) ) {
mondays.add( monday );
// Set up the next loop.
monday = monday.plusWeeks( 1 );
}
By the way, usually the wise approach in handling a span of time is Half-Open where the beginning is inclusive while the ending is exclusive. So in the code above we are running up to, but not including, the stop date.
If the ending is inclusive, use the negation of isAfter e.g.
while( !monday.isAfter( stop ) ) {
//...
}
Here, monday is not after stop means it is before or up to stop.
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
This code takes to string dates and gives the number of sundays and also all the sunday's dates
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class FindAllSundays {
public static int getNumberofSundays(String d1, String d2) throws Exception { // object
// in
// Date
// form
Date date1 = getDate(d1);
Date date2 = getDate(d2);
Calendar c1 = Calendar.getInstance();
c1.setTime(date1);
Calendar c2 = Calendar.getInstance();
c2.setTime(date2);
int sundays = 0;
while (c2.after(c1)) {
// System.out.println(" came here ");
//checks to see if the day1 ....so on next days are sundays if sunday goes inside to increment the counter
if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
System.out.println(c1.getTime().toString() + " is a sunday ");
sundays++;
}
c1.add(Calendar.DATE, 1);
}
System.out.println("number of sundays between 2 dates is " + sundays);
return sundays;
}
// converts string to date
public static Date getDate(String s) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(s);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
public static void main(String[] arg) throws Exception {
System.out.println(" " + getNumberofSundays("2005-10-07", "2006-10-01"));
}
}
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class Get_time {
public ArrayList<LocalDate> getmondays(String s,String e)
{
LocalDate start = LocalDate.parse(s);
LocalDate end = LocalDate.parse(e);
List<LocalDate> totalDates_Mondays = new ArrayList<>();
while (!start.isAfter(end)) {
totalDates_Mondays.add(start);
start = start.plusWeeks(1);
}
return (ArrayList<LocalDate>) totalDates_Mondays;
}
public static void main(String ...s1) {
String mon_start = "1600-08-01";
String mon_end= "2016-12-29";
Get_time t=new Get_time();
System.out.println(t.getmondays(mon_start,mon_end));
}
}
In Java 8 using Stream ,
LocalDate startDate = LocalDate.of(2019, 2, 1);
LocalDate endDate = LocalDate.of(2019, 2, 28);
long numOfDays = ChronoUnit.DAYS.between(startDate, endDate);
List<LocalDate> daysRange = Stream.iterate(startDate, date -> date.plusDays(1)).limit(numOfDays).filter( date -> date.getDayOfWeek()==DayOfWeek.MONDAY ).collect(Collectors.toList());
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class Test {
public static void main(String[] args) throws ParseException {
Calendar dateFromNet = strToCal("11-MAR-2004", "dd-MMM-yyyy");
Calendar IEndTime = strToCal("20-05-2004", "dd-mm-yyyy");
if (dateFromNet.after(IEndTime) ) {
System.out.println(dateFromNet);
System.out.println(IEndTime);
System.out.println("not true: 11-MAR-2004(11-3-2004) > 20-05-2004 ");
}
}
private static Calendar strToCal(String date, String format) throws ParseException {
SimpleDateFormat input = new SimpleDateFormat(format);
input.setTimeZone(TimeZone.getTimeZone("GMT"));
Date d = (Date) input.parse(date);
Calendar c = Calendar.getInstance();
c.setTime(d);
return c;
}
}
This test shows
dateFromNet.after(IEndTime) == true
i.e. 11-03-2004 is after 20-05-2004
What have I done wrong?
Calendar IEndTime = strToCal("20-05-2004", "dd-mm-yyyy");
mm is for milliseconds; make those capitol M, like this:
Calendar IEndTime = strToCal("20-05-2004", "dd-MM-yyyy");
The letter, m and M have different meanings as shown in the following table:
Letter
Date or Time Component
Presentation
Examples
m
Minute in hour
Number
30
M
Month in year
Month
July; Jul; 07
So, the root cause of the problem is using m instead of M in the pattern, dd-mm-yyyy.
java.time
The legacy date-time API (java.util date-time types and their formatting type, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
Demo of the modern API:
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZonedDateTime dateFromNet = strToZdt("11-MAR-2004", "d-MMM-u");
ZonedDateTime IEndTime = strToZdt("20-05-2004", "d-M-u");
if (dateFromNet.isAfter(IEndTime)) {
System.out.println("11-MAR-2004 > 20-05-2004");
} else if (dateFromNet.isBefore(IEndTime)) {
System.out.println("11-MAR-2004 < 20-05-2004");
} else {
System.out.println("11-MAR-2004 = 20-05-2004");
}
}
private static ZonedDateTime strToZdt(String date, String format) {
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern(format)
.toFormatter(Locale.ENGLISH);
LocalDate localDate = LocalDate.parse(date, dtf);
return localDate.atStartOfDay(ZoneId.of("Etc/UTC"));
}
}
Output:
11-MAR-2004 < 20-05-2004
If at all you need an object of java.util.Calendar from this object of ZonedDateTime, you can do so as follows:
Calendar calendar = Calendar.getInstance();
calendar.setTime(Date.from(dateFromNet.toInstant()));
Learn more about the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.