Saving Dates to a serialized file - java

Im trying to save two dates into a serialized . bin file. I use the Calendar class to get the current date then I add 30 days onto it. So I try to save two date variables fd (First Date) and ed (Expiration Date). If I change them to Strings in the expiration_date_serial file they work, but when I try to save them as Date they throw errors on these 2 lines:
exp_date.fd = current_formateddate;
exp_date.ed = formateddate;
Error:
incompatible types: java.lang.String cannot be converted to java.util.Date
Runnable Class:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class GetCurrentDate {
public static void main(String[] args) {
// get current date
DateFormat currentdateFormat = new SimpleDateFormat("MM/dd/yy");
Date current_date = new Date();
String current_formateddate = currentdateFormat.format(current_date);
System.out.println("Current date: " + (current_formateddate));
// ADD 30 days to the current date
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, 30);
Date d = c.getTime();
String formateddate = dateFormat.format(d);
System.out.println("+ 30 days: " + formateddate);
// Serialization start
expiration_date_serial exp_date = new expiration_date_serial();
exp_date.fd = current_formateddate;
exp_date.ed = formateddate;
String fileName = "data.bin";
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream(fileName));
os.writeObject(exp_date);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done writing...");
try {
ObjectInputStream is = new ObjectInputStream(new FileInputStream(
fileName));
expiration_date_serial p = (expiration_date_serial) is.readObject();
System.out.println("First Date = " + p.fd +
" Expiration Date = " + p.ed);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Other class:
import java.io.Serializable;
import java.util.Date;
public class expiration_date_serial implements Serializable {
public Date fd;//First Date
public Date ed;//Expiration Date
}

In Java, you cannot assign a value of type String to a field of type Date, that's why the error. It happens even before the serialization.
Your most obvious options are:
change a type of the field to String
don't convert Date objects to String and save them as is
You should decide what suits your needs better.

tl;dr
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.plusDays( 30 )
.toString()
Details
The Answer by Orlangure is correct, about assigning across types.
Also, other problems include:
Using old outmoded legacy classes for date-time handling.
Poor choice of format for serialized date values.
Incorrectly choosing to use a date-time class for a date-only value.
java.time
The old date-time classes are poorly-designed, confusing, and troublesome. Avoid them. Now legacy, supplanted by the java.time classes.
ISO 8601
The ISO 8601 standard defines textual formats for date-time values. These formats are unambiguous, intuitive across cultures, and practical. The standard format for a date-only value is YYYY-MM-DD such as 2016-10-23.
The java.time classes use ISO 8601 by default when parsing and generating Strings to represent their date-time values.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without 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.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Strings
To generate an ISO 8601 compliant String, simply call toString.
String output = today.toString(); // 2016-10-23
To parse, simply call parse.
LocalDate ld = LocalDate.parse( "2016-10-23" );
Date math
You can add or subtract amounts of time. Just call the plus… and minus… methods.
LocalDate thirtyDaysAgo = ld.minusDays( 30 );
LocalDate oneMonthAgo = ld.minusMonths( 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 java.time.
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.

Related

How to reformat time format?

I am working on android project and i receive from API the time in format like this "10:12:57 am" (12 hour format) and I want to display it in format "10:12" just like this (on a 24 hour clock). How to reformat that time?
So 12:42:41 am should become 00:42. And 02:13:39 pm should be presented as 14:13.
Using java.time (Modern Approach)
String str = "10:12:57 pm";
DateTimeFormatter formatter_from = DateTimeFormatter.ofPattern( "hh:mm:ss a", Locale.US ); //Use pattern symbol "hh" for 12 hour clock
LocalTime localTime = LocalTime.parse(str.toUpperCase(), formatter_from );
DateTimeFormatter formatter_to = DateTimeFormatter.ofPattern( "HH:mm" , Locale.US ); // "HH" stands for 24 hour clock
System.out.println(localTime.format(formatter_to));
See BasilBourque answer below and OleV.V. answer here for better explanation.
Using SimpleDateFormat
String str = "10:12:57 pm";
SimpleDateFormat formatter_from = new SimpleDateFormat("hh:mm:ss a", Locale.US);
//Locale is optional. You might want to add it to avoid any cultural differences.
SimpleDateFormat formatter_to = new SimpleDateFormat("HH:mm", Locale.US);
try {
Date d = formatter_from.parse(str);
System.out.println(formatter_to.format(d));
} catch (ParseException e) {
e.printStackTrace();
}
If your input is 10:12:57 am, output will be 10:12. And if string is 10:12:57 pm, output will be 22:12.
tl;dr
LocalTime // Represent a time-of-day, without a date and without a time zone.
.parse( // Parse an input string to be a `LocalTime` object.
"10:12:57 am".toUpperCase() , // The cultural norm in the United States expects the am/pm to be in all-uppercase. So we convert our input value to uppercase.
DateTimeFormatter.ofPattern( "hh:mm:ss a" , Locale.US ) // Specify a formatting pattern to match the input.
) // Returns a `LocalTime` object.
.format( // Generate text representing the value in this date-time object.
DateTimeFormatter.ofPattern( "HH:mm" , Locale.US ) // Note that `HH` in uppercase means 24-hour clock, not 12-hour.
) // Returns a `String`.
10:12
java.time
The modern approach uses the java.time classes that years ago supplanted the terrible Date & Calendar & SimpleDateFormat classes.
The LocalTime class represents a time-of-day in a generic 24-hour day, without a date and without a time zone.
Parse your string input as a LocalTime object.
String input = ( "10:12:57 am" );
DateTimeFormatter fInput = DateTimeFormatter.ofPattern( "HH:mm:ss a" , Locale.US );
LocalTime lt = LocalTime.parse( input.toUpperCase() , fInput ); // At least in the US locale, the am/pm is expected to be in all uppercase: AM/PM. So we call `toUppercase` to convert input accordingly.
lt.toString(): 10:12:57
Generate a String with text in the hour-minute format you desire. Note that HH in uppercase means 24-hour clock.
DateTimeFormatter fOutput = DateTimeFormatter.ofPattern( "HH:mm" , Locale.US );
String output = lt.format( fOutput );
output: 10:12
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.
Try this:
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm:ss a");
try {
Date date = parseFormat.parse("10:12:57 pm");
System.out.println(parseFormat.format(date) + " = " + displayFormat.format(date));
}
catch (Exception e) {
e.printStackTrace();
}
The gives:
10:12:57 pm = 22:12
You can use such formatters:
SimpleDateFormat formatterFrom = new SimpleDateFormat("hh:mm:ss aa");
SimpleDateFormat formatterTo = new SimpleDateFormat("HH:mm");
Date date = formatterFrom.parse("10:12:57 pm");
System.out.println(formatterTo.format(date));
String str ="10:12:57 pm";
SimpleDateFormat formatter_from = new SimpleDateFormat("hh:mm:ss aa", Locale.US);
SimpleDateFormat formatter_to = new SimpleDateFormat("HH:mm",Locale.US);
try {
Date d = formatter_from.parse(str);
System.out.println(formatter_to.format(d));
} catch (ParseException e) {
e.printStackTrace();
}

How to compare time string with current time in java?

I have a time string like "15:30" i want to compare that string with the current time.
Please suggest something easy.
And how to get the current time in hour minute format("HH:mm")
tl;dr
LocalTime
.now()
.isAfter(
LocalTime.parse( "15:30" )
)
Details
You should be thinking the other way around: How to get that string turned into a time value. You would not attempt math by turning your numbers into strings. So too with date-time values.
Avoid the old bundled classes, java.util.Date and .Calendar as they are notoriously troublesome, flawed both in design and implementation. They are supplanted by the new java.time package in Java 8. And java.time was inspired by Joda-Time.
Both java.time and Joda-Time offer a class to capture a time-of-day without any date to time zone: LocalTime.
java.time
Using the java.time classes built into Java, specifically LocalTime. Get the current time-of-day in your local time zone. Construct a time-of-day per your input string. Compare with the isBefore, isAfter, or isEqual methods.
LocalTime now = LocalTime.now();
LocalTime limit = LocalTime.parse( "15:30" );
Boolean isLate = now.isAfter( limit );
Better to specify your desired/expected time zone rather than rely implicitly on the JVM’s current default time zone.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
LocalTime now = LocalTime.now( z ); // Explicitly specify the desired/expected time zone.
LocalTime limit = LocalTime.parse( "15:30" );
Boolean isLate = now.isAfter( limit );
Joda-Time
The code in this case using the Joda-Time library happens to be nearly the same as the code seen above for java.time.
Beware that the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
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….
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.
Just compare the strings as normal like so:
String currentTime = new SimpleDateFormat("HH:mm").format(new Date());
String timeToCompare = "15:30";
boolean x = currentTime.equals(timeToCompare);
If the times are the same x will be true if they are not x will be false
Following would get the time. You can than use it to compare
String currentTime=new SimpleDateFormat("HH:mm").format(new Date());
I have a similar situation where I need to compare time string like "15:30" with the current time.
I am using Java 7 so I can not use Basil Bourque's solution.
So I have implemented one method which takes one string like "15:30" and
check with current time and returns true if current time is after input time.
public static boolean checkSlaMissedOrNot(String sla) throws ParseException {
boolean slaMissedOrnot = false;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(sla.substring(0, 2)));
cal.set(Calendar.MINUTE, Integer.parseInt(sla.substring(3)));
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
if (Calendar.getInstance().after(cal)) {
System.out.println("it's SLA missed");
slaMissedOrnot = true;
} else {
System.out.println("it's fine & not SLA missed");
}
return slaMissedOrnot;
}
Calendar has other use full methods like after(Object when)
Returns whether this Calendar represents a time after the time represented by the specified Object.
You can use this method also to compare time string with the current time.
So my Solution is a little bit different, Its starts with creating an clock with the current time, and testing the hour agaisnt a user defined int.
public void TextClockWindow() {
this.pack();
javax.swing.Timer t = new javax.swing.Timer(1000, (ActionEvent e) -> {
Calendar calendar = new GregorianCalendar();
String am_pm;
calendar.setTimeZone(TimeZone.getDefault());
Calendar now = Calendar.getInstance();
int h = now.get(Calendar.HOUR_OF_DAY);
int m = now.get(Calendar.MINUTE);
int s = now.get(Calendar.SECOND);
if (calendar.get(Calendar.AM_PM) == 0) {
am_pm = "AM";
} else {
am_pm = "PM";
} // Code to Determine whether the time is AM or PM
Clock.setText("" + h + ":" + m + " " + am_pm);
if(h < 5) { //int here which tests agaisnt the hour evwery second
System.out.println("Success");
} else {
System.out.println("Failure");
}
});
t.start();
}
Try this
public static String compareTime(String d) {
if (null == d)
return "";
try {
SimpleDateFormat sdf= new SimpleDateFormat("HH:mm");
d = sdf.format(new Date());
} catch (Exception e) {
e.printStackTrace();
}
return d;
}
then you can compare with your string
Here is my example to compare before and after current time :
MainActivity.java
Button search = (Button) findViewById(R.id.searchBus);
SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm");
String limit = "23:00";
Date limitBus=null;
try {
limitBus = sdfDate.parse(limit);
} catch (ParseException e) {
e.printStackTrace();
}
String start = "07:15";
Date startBus=null;
try {
startBus = sdfDate.parse(start);
} catch (ParseException e) {
e.printStackTrace();
}
String user_time = getCurrentTimeStamp();
Date now = null;
try {
now = sdfDate.parse(user_time);
} catch (ParseException e) {
e.printStackTrace();
}
if (now.after(limitBus)||now.before(startBus)){
Toast.makeText(this, "Bus Operation Hours : 7:15AM - 11.00PM", Toast.LENGTH_LONG).show();
search.setEnabled(false);
}
else
{
search.setEnabled(true);
}
//get current time method
public static String getCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
This code will check User Inputted time with current system time and will return time difference in long value.
public long getTimeDifferenceInMillis (String dateTime) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long currentTime = new Date().getTime();
long endTime = 0;
try {
//Parsing the user Inputed time ("yyyy-MM-dd HH:mm:ss")
endTime = dateFormat.parse(dateTime).getTime();
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
if (endTime > currentTime)
return endTime - currentTime;
else
return 0;
}
The user should pass the time in "yyyy-MM-dd HH:mm:ss" format.

How to convert date to string and to date again?

Hi i want to convert the current date to this format YYYY-MM-DD. However, it will convert the date into String format, but i want to convert it back into Date format. So can anyone advise on this?
This is my code so far
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String datestring = dateFormat.format(date);
try this:
String DATE_FORMAT_NOW = "yyyy-MM-dd";
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
String stringDate = sdf.format(date );
try {
Date date2 = sdf.parse(stringDate);
} catch(ParseException e){
//Exception handling
} catch(Exception e){
//handle exception
}
Use DateFormat#parse(String):
Date date = dateFormat.parse("2013-10-22");
tl;dr
How to convert date to string and to date again?
LocalDate.now().toString()
2017-01-23
…and…
LocalDate.parse( "2017-01-23" )
java.time
The Question uses troublesome old date-time classes bundled with the earliest versions of Java. Those classes are now legacy, supplanted by the java.time classes built into Java 8, Java 9, and later.
Determining today’s date requires a time zone. For any given moment the date varies around the globe by zone.
If not supplied by you, your JVM’s current default time zone is applied. That default can change at any moment during runtime, and so is unreliable. I suggest you always specify your desired/expected time zone.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;
ISO 8601
Your desired format of YYYY-MM-DD happens to comply with the ISO 8601 standard.
That standard happens to be used by default by the java.time classes when parsing/generating strings. So you can simply call LocalDate::parse and LocalDate::toString without specifying a formatting pattern.
String s = ld.toString() ;
To parse:
LocalDate ld = LocalDate.parse( s ) ;
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….
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 function
public static Date StringToDate(String strDate) throws ModuleException {
Date dtReturn = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
try {
dtReturn = simpleDateFormat.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return dtReturn;
}
Convert Date to String using this function
public String convertDateToString(Date date, String format) {
String dateStr = null;
DateFormat df = new SimpleDateFormat(format);
try {
dateStr = df.format(date);
} catch (Exception ex) {
System.out.println(ex);
}
return dateStr;
}
From Convert Date to String in Java
. And convert string to date again
public Date convertStringToDate(String dateStr, String format) {
Date date = null;
DateFormat df = new SimpleDateFormat(format);
try {
date = df.parse(dateStr);
} catch (Exception ex) {
System.out.println(ex);
}
return date;
}
From Convert String to date in Java

Convert date string to a particular date format "dd-MM-yyyy" in Java

I have multiple contacts with birth dates and all are synced with the mobile device. Now the problem is all contacts have different birthday formats and I want to display all of the birthday dates in a specific format like "dd-MM-yyyy".
So for example, one synchronized contact has birthday like "1990-02-07" or "1988-06-15T22:00:00.000Z" or "12-02-1990" etc...
Then all of these dates should be displayed in a specific format "dd-MM-yyyy".
So how can I resolve this issue?
Any suggestion will be appreciated.
Simply using SimpleDateFormat class. Something like:
Date d = Calendar.getInstance().getTime(); // Current time
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // Set your date format
String currentData = sdf.format(d); // Get Date String according to date format
Here you can see details and all supported format:
http://developer.android.com/reference/java/text/SimpleDateFormat.html
I somehow understand what you're problem is here. You can try the long way like splitting the strings with "-" and store it in array then check each string in the array, parse it to int then perform conditional statements.
assuming that the ones you gave has the following formats
"1990-02-07" year-month-day
"1988-06-15T22:00:00.000Z" year-month-dayTtimeZ
"12-02-1990" month-day-year
you can try something like this.
public String convert(String s){
SimpleDateFormat newformat = new SimpleDateFormat("dd-MM-yyyy");
try{
if(s.contains("T")){
String datestring = s.split("T")[0];
SimpleDateFormat oldformat = new SimpleDateFormat("yyyy-MM-dd");
String reformattedStr = newformat.format(oldformat.parse(datestring));
return reformattedStr;
}
else{
if(Integer.parseInt(s.split("-")[0])>13){
SimpleDateFormat oldformat = new SimpleDateFormat("yyyy-MM-dd");
String reformattedStr = newformat.format(oldformat.parse(s));
return reformattedStr;
}
else{
SimpleDateFormat oldformat = new SimpleDateFormat("MM-dd-yyyy");
String reformattedStr = newformat.format(oldformat.parse(s));
return reformattedStr;
}
}
}
catch (Exception e){
return null;
}
}
ISO 8601
Now the problem is all contacts have different birthday formats
That is the real problem: storing date-time values in various formats.
When serializing date-time values to text, always use standard ISO 8601 formats. These formats are sensible and practical, avoiding ambiguity, being easy to parse by machine as well as readably by humans across cultures.
The java.time classes use these standard formats by default when parsing/generating strings.
java.time
The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes. Avoid the legacy Date, Calendar, SimpleDateFormat, and related classes.
So for example, one synchronized contact has birthday like "1990-02-07" or "1988-06-15T22:00:00.000Z" or "12-02-1990" etc...
Parsing any conceivable date-time format is impossible because of ambiguity. For example, is 01-02-1990 representing January 2nd or February 1st?
You can guess if you wish, though this may be ill-advised depending on how important accuracy means to your business problem.
Define a bunch of formatting patterns with DateTimeFormatter. Try each. When the DateTimeParseException is thrown, move on to the next pattern until one works.
You can use string length to help guide the guessing.
List < DateTimeFormatter > dateFormatters = new ArrayList <>( 2 );
dateFormatters.add( DateTimeFormatter.ofPattern( "uuuu-MM-dd" ) ); // BEWARE of ambiguity in these formatters regarding month-versus-day.
dateFormatters.add( DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) );
String input = "1990-02-07";
// String input = "12-02-1990" ;
if ( null == input )
{
throw new IllegalArgumentException( "Passed null argument where a date-time string is expected. Message # c7a4fe0e-9500-45d5-a041-74d457381008." );
} else if ( input.length() <= 10 )
{
LocalDate ld = null;
for ( DateTimeFormatter f : dateFormatters )
{
try
{
ld = LocalDate.parse( input , f );
System.out.println( ld );
} catch ( Exception e )
{
// No code here.
// We purposely ignore this exception, moving on to try the next formatter in our list.
}
}
} else if ( ( input.length() > 10 ) && input.substring( input.length() - 1 ).equalsIgnoreCase( "Z" ) ) // If over 10 in length AND ends in a Z.
{
Instant ld = null;
try
{
ld = Instant.parse( input ); // Uses `DateTimeFormatter.ISO_INSTANT` formatter.
} catch ( Exception e )
{
throw new IllegalArgumentException( "Unable to parse date-time string argument. Message # 0d10425f-42f3-4e58-9baa-84ff949e9574." );
}
} else if ( input.length() > 10 )
{
// TODO: Define another list of formatters to try here.
} else if ( input.length() == 0 )
{
throw new IllegalArgumentException( "Passed empty string where a date-time string is expected. Message # 0ffbd9b6-8905-4e28-a732-0f402d4673df." );
} else // Impossible-to-reach, for defensive programming.
{
throw new RuntimeException( "ERROR - Unexpectedly reached IF-ELSE when checking input argument. Message # 6228d9e0-047a-4b83-8916-bc526e0fd22d." );
}
System.out.println("Done running.");
1990-02-07
Done running.
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, 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.

Joda time - all mondays between two dates

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());

Categories

Resources