String to GregorianCalendar [duplicate] - java

This question already has answers here:
Convert a string to a GregorianCalendar
(2 answers)
Closed 9 years ago.
i have this code:
String start = startBox.getText();
String finish = finishBox.getText();
myprogram.addPeriod(start, finish)
addPeriod method has 2 GregorianCalendar as parameters, so how to convert the 2 string into GregorianCalendar?
I tried a couple of ways that i read on this site but they don't work with me
startBox and finishBox are 2 JTextField filled with date in this format: YYYY/MM/DD.

How about this, the steps are self-explanatory but you want to have a handle on an instance of SimpleDateFormat of the pattern in which you have your date.
Parse your Strings to get a Date instance and set your specific date to the respective Calendar instances.
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
String start = startBox.getText();
String finish = finishBox.getText();
GregorianCalendar cal1 = new GregorianCalendar();
cal1.setTime(format.parse(start));
GregorianCalendar cal2 = new GregorianCalendar();
cal1.setTime(format.parse(finish));
myprogram.addPeriod(cal1, cal2);
}
} catch (ParseException e) {
e.printStackTrace();
}

Related

I have created a method to add minutes to date time but does not as expected in Java [duplicate]

This question already has answers here:
Parsing a string to date format in java defaults date to 1 and month to January
(2 answers)
Is SimpleDateFormat in Java work incorrect or I did any mistake? See code sample [duplicate]
(2 answers)
Why is the month changed to 50 after I added 10 minutes?
(13 answers)
Closed 3 years ago.
This is a java code where it adds the date with time hours and minutes if a possible day to
timeAddition("06/20/2019;23:30", 60, "m")
public static String timeAddition(String TimeAndDate, int addTime, String units_M_H) {
try {
String returnTime = TimeAndDate;
final long ONE_MINUTE_IN_MILLIS = 60000;
DateFormat dateFormat = new SimpleDateFormat("MM/dd/YYYY;HH:mm");
Date date = dateFormat.parse(TimeAndDate);
Calendar Cal = Calendar.getInstance();
Cal.setTime(date);
if (units_M_H.trim().equalsIgnoreCase("h")) {
Cal.add(Calendar.HOUR_OF_DAY, addTime);
returnTime = dateFormat.format(Cal.getTime()).toString();
} else if (units_M_H.trim().equalsIgnoreCase("m")) {
long timeInMili = date.getTime();
date = new Date(timeInMili + (addTime * ONE_MINUTE_IN_MILLIS));
returnTime = dateFormat.format(date);
}
return returnTime;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
The expected output is 06/21/2019;00:30 but the actual output is 12/31/2019;00:30
java.time
Do not reinvent the wheel, Java already has all instruments to do such operations. See the java.time package of classes built into Java. See Tutorial.
String timestamp = "06/20/2019;23:30";
LocalDateTime ldt = LocalDateTime.parse(timestamp,
DateTimeFormatter.ofPattern("MM/dd/yyyy;HH:mm"));
System.out.println(ldt);
LocalDateTime ldt2 = ldt.plus(60L, ChronoUnit.MINUTES);
System.out.println(ldt2);
Will print that you expect.
2019-06-20T23:30
2019-06-21T00:30
Hope this helps!
Use yyyy for year.
YYYY represents week year.

JAVA - Format a custom string using SimpleDateFormat [duplicate]

This question already has answers here:
How to parse a date? [duplicate]
(5 answers)
Java string to date conversion
(17 answers)
Closed 5 years ago.
I'm having trouble formatting a custom String back to a Date object. What i have:
String customString = "October 14, 2015;
Date date = new Date();
SimpleDateFormat s = new SimpleDateFormat("MM-dd-yyyy");
try {
date = s.parse(customString);
} catch (ParseException e) {
e.printStackTrace();
}
I always get a unappeasable date exception. Any pointers of what i'm doing wrong is appreciated.
Your pattern must be: new SimpleDateFormat("MMM dd,yyyy");
For more informations about SimpleDateFormat see the javadoc
Read the docs, https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.
The argument of the constructor should have the format of the date you want to input.
For instance, if you want the full month name should have "MMMMM".
Just make the following change and the program will work.
SimpleDateFormat s = new SimpleDateFormat("MMMMM dd, yyyy");

Add days to date format MM/dd/yyyy in selenium webdriver [duplicate]

This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 7 years ago.
The question is simple, how to add days to this date format:
MM/dd/yyyy like 11/06/2015
You can do something like this:
String format = "mm/dd/yyyy";
String date = "11/06/2015";
SimpleDateFormat simpleFormat = new SimpleDateFormat("mm/dd/yyyy");
java.text.DateFormat df = new java.text.SimpleDateFormat(format);
java.util.Calendar calendar = java.util.Calendar.getInstance();
try {
calendar.setTime(df.parse(date));
calendar.add(java.util.Calendar.DAY_OF_MONTH, +1);
String formatted = simpleFormat.format(calendar.getTime());
System.out.println(formatted);
} catch (Exception ex) {
System.out.println("Error: " + ex.toString());
}

How do I parse a date string into a Joda DateTime object for java? [duplicate]

This question already has answers here:
Converting a date string to a DateTime object using Joda Time library
(10 answers)
Closed 7 years ago.
The code below is the best I have come up with so far. The .setTime() methods are throwing a exception. Is there a better way to do this or correct this?
String format = "MM/dd/yyyy";
DateTime test = new DateTime();
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy");
SimpleDateFormat formater = new SimpleDateFormat(format);
String startDateString = "09/10/2015";
String endDateString = "09/20/2015";
Date startDate = null;
Date endDate = null;
Calendar sampleDateStart = null;
Calendar sampleDateEnd = null;
try{
startDate = formater.parse(startDateString);
endDate = formater.parse(endDateString);
sampleDateStart.setTime(startDate);
sampleDateEnd.setTime(endDate);
}catch(Exception e){
System.out.println(e.getMessage());
}
You already created the DateTimeFormatter that your need, so just use it:
DateTimeFormatter formater = DateTimeFormat.forPattern("MM/dd/yyyy");
DateTime startDateTime = formater.parseDateTime("09/10/2015");
DateTime endDateTime = formater.parseDateTime("09/20/2015");
No need for a SimpleDateFormat or a Calendar.
Note: I fixed the creation of the DateTimeFormatter to Joda, since you were doing it the Java 8 way.
Seems fine if you fix the initialization of the Calendar variables:
Calendar sampleDateStart = Calendar.getInstance();
Calendar sampleDateEnd = Calendar.getInstance();
The problem would have been more obvious if you had used the correct exception type as recommended,
instead of the generic Exception,
and printing the stack trace instead of e.getMessage():
try {
startDate = formater.parse(startDateString);
endDate = formater.parse(endDateString);
sampleDateStart.setTime(startDate);
sampleDateEnd.setTime(endDate);
} catch (ParseException e) {
e.printStackTrace();
}
The stack trace would have told you the exact line where NullPointerException was thrown.

Adding n number of days in a given particular date [duplicate]

This question already has answers here:
Adding days to a date in Java [duplicate]
(6 answers)
Closed 8 years ago.
String dt="2014-04-25";
I want to add n number of days in this date ... I have searched a lot but was not able to get any good working code....
I have tried SimpleDateFormat but it is not working so please help me with the code....
You can do it using joda time library
import org.joda.time;
String dt="2014-04-25";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime dateTime = formatter.parseDateTime(dt);
DateTime oneDayPlus = dateTime.plusDays(1);
String oneDayPlusString = oneDayPlus.toString(formatter); // This is "2014-04-26"
oneDayPlus would give you the object you need.
Again, this needs you to use an extra jar file, so use it if you can introduce adding a new library.
Remember String != Date they don't have anything in common (ok, exclude the fact that a string could represent a Date ok?)
If you want to add days to a String you could convert it to a Date and use normal APIs to add days to it.
And here we use SimpleDateFormat which is used to create from a patten string a date
String dt = "2014-04-25";
// yyyy-MM-dd
// year-month-day
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
try
{
Date date = format.parse(dt);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, 5);
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
}
catch (ParseException e)
{
System.out.println("Wrong date");
}
yyyy-MM-dd is our patten which corrisponds to our string.
format.parse(dt);
wil try to create a Date object from the string we passed, if it fails it throw an ParseException. (If you want to check if it works just try to pass an invalid string)
Then we create a new Calendar instance and set the date to the date we created (which corrisponds to the the date in our string) and add five days to our date.. and here we go. Now calendar will refer to the 30-04-2014.
You can replace the
calendar.add(Calendar.DAY_OF_MONTH, 5);
with
calendar.add(Calendar.DAY_OF_MONTH, n);
If you want and it will add n days.

Categories