Concatenating and converting JCombo integer value to date - java

I read somewhere in MySQL reference pages that the DATE data type accepts either a date in 'YYYY-MM-DD' or YYYYMMDD. So, either a String or an int
I have 3 JComboBoxes for day, month, and year.
So I converted them to int
int myDay = Integer.parseInt( dayJcbx.getSelectedItem().toString() );
int myYear = Integer.parseInt( yearJcbx.getSelectedItem().toString() );
int myMonth = Integer.parseInt( monthJcbx.getSelectedItem().toString() );
and tried to concatenate them as one int
int birthdate = Integer.parseInt(myYear+""+myMonth+""+myDay);
to match mySQLs format which is YYYYMMDD but still failed to insert it to the database. I get this message when I tried to insert April 3, 1987 as sample date.
Then I tried to use calendar class to add the 0 in month MM but still failed.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, myYear);
calendar.set(Calendar.MONTH, myMonth - 1);
calendar.set(Calendar.DATE, myDay);
Please also tell me which is correct for inserting date through CallableStatement cs.setDate(1,"date") or cs.setString(1,"date")
I hope you can help me fix this because I'm now stuck just because of date.
I recently tried jodatime.
By the way, my stored procedure looks like this.
CREATE DEFINER=`root`#`localhost` PROCEDURE `register`(
p_dateOfBirth DATE)
BEGIN
DECLARE EXIT HANDLER FOR sqlexception
BEGIN
ROLLBACK;
RESIGNAL;
END;
START TRANSACTION;
INSERT INTO registration(dateOfBirth)
VALUES(p_dateOfBirth);
COMMIT;

As per your message
... value: '198743'
Definitively '198743' does not seem a date in YYYYMMDD format (8 mandatory positions), there are missing a couple of zeroes before 4 and 3 to get 19870403 what **is a correct YYYYMMDD format
Fast way (if your combos give "04" instead of "4" per April):
String myYear = yearJcbx.getSelectedItem();
String myMonth = monthJcbx.getSelectedItem();
String myDay = dayJcbx.getSelectedItem();
int birthdate = Integer.parseInt(myYear+myMonth+myDay);
If you cannot change return result of combos, try this workaround
// pad the strings with 0, 2 positions mandatory
int myYear = Integer.parseInt( yearJcbx.getSelectedItem().toString() );
String myMonth = String.format("%02d", Integer.parseInt(monthJcbx.getSelectedItem()));
String myDay = String.format("%02d", Integer.parseInt(dayJcbx.getSelectedItem());
int birthdate = Integer.parseInt(myYear+myMonth+myDay);
DEMO:
String myDay = String.format("%02d", Integer.parseInt("4"));
System.out.println(myDay);
PRINTS:
04

You can do like this using Java 8 DateTime API
Imports needed
import java.sql.Date;
import java.time.LocalDate;
Code:
LocalDate localDate = LocalDate.of(myYear,myMonth,myDay);
Date date = Date.valueOf(localDate);
cs.setDate(1,date);

Related

Trouble with formatting a string that contains a date in java

Basically I have a string that includes a date and I am trying to have it print out a 0 infront of the months and days that only have 1 digit. so 1 would print out 01. This is the code I have written but i get an error that is saying : Exception in thread "main"java.util.IllegalFormatConversionException: d != java.lang.String.
day = String.format("%02d", day);
Assuming that day is an int
then with
day = String.format("%02d", day);
you are trying to re-assign a String to the int
try
String dayStr = String.format("%02d", day);
edit
So as day is already a String then format("%02d", day); will not work d means it is an int
So convert it to a int first
day = String.format("%02d", Integer.valueOf (day));
If I am allowed to take a step back: this may smell a bit like a design problem. You shouldn’t store your date in a string in dd/mm/yyyy format. You should store your date in a LocalDate. Of course, if the date is string input, for instance from the user, you need to accept is as such. Then convert to LocalDate:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
String dateString = "1/9/2019";
LocalDate date = LocalDate.parse(dateString, dateFormatter);
For formatting the day of month into two digits use another DateTimeFormatter:
DateTimeFormatter dayOfMonthFormatter = DateTimeFormatter.ofPattern("dd");
String dayString = date.format(dayOfMonthFormatter);
System.out.println("Day in two digits is " + dayString);
Output in this case is:
Day in two digits is 01
Or to output the full date with two-digit day and two-digit month:
DateTimeFormatter outputDateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
String outputString = date.format(outputDateFormatter);
System.out.println("Output: " + outputString);
Output: 01/09/2019
Link: Oracle tutorial: Date Time.

Is there a method to add months to a date fetching the below expected

Is there a mechanism or a method in Joda Time itself/or some other API through which i can achieve the same.???
Please suggest?
Input Date: 2018-04-30
Used Joda Time like this gives output: 2018-05-30
Expected Date : 2018-05-31
Edited Again
Want to know if it will be alright to say and do like this meaning
if the input date is the last date(will use the algos shared) then
fetch the last date of the next month and
else if input date is anything else then use plusMonths method
right??
String startDate = "2018-04-30";
DateTime startDateTime = new DateTime(startDate, DateTimeZone.UTC);
int repeatEvery = 1;
int numOfPayments = 2;
String endDate = startDateTime.plusMonths(repeatEvery * (numOfPayments-1)).toString();
System.out.println(endDate);
Using the Java Time API, it is quite simple to get the last day of a month using a TemporalAdjuster, the API come with some already define, like TemporalAdjusters.lastDayOfMonth().
So here is a simple example on how to get the last day of the next month (based on today).
LocalDate date = LocalDate.now()
.plus(1, ChronoUnit.MONTHS)
.with(TemporalAdjusters.lastDayOfMonth()));
This is pretty verbose to be understandable I believe.
To parse the String into a LocalDate. Simply replace now() by parse() like :
LocalDate.parse("2019-05-03", DateTimeFormatter.ISO_DATE);
Using :
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
This is actually already an answer in the duplicate proposed, just need to scoll a bit to find it. It lakes some visibility !!
You could do this by the Calendar
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String startDate = "2018-04-30";
int repeatEvery = 1;
int numOfPayments = 2;
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.setTime(sdf.parse(startDate));
cal.add(Calendar.MONTH, repeatEvery * (numOfPayments - 1));
System.out.println("intRes: "+sdf.format(cal.getTime()));
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
String endDate = sdf.format(cal.getTime());
System.out.println(endDate);
out:
intRes: 2018-05-30
2018-06-01
I dont know why this is giving me the 2018-06-01 ?

How to select selected month data

I have a HTML form inside which i have a Date-picker which is only for month and Year, so user is selecting month and year then submitting the form so at my server end i.e Java Servlet i am getting that value by request.getParameter
and it is giving 08/2018 08 is the month and 2018 is year
so in my server end i have to write a query which can give me the data of the month-year which is selected
query i am thinking of is something like this
select cashier from tableName where billdate=''
so what value should i give to bill date so that it gives me data for the selected month like currently i have month as 08 and year as 2018
Note:- i am using MySql5.5
EDIT
As i can use this query also :- SELECT * FROM tableName WHERE YEAR(billdate) = 2018 AND MONTH(billdate) = 8
but the issue is i am getting date as 08/2019 how can i split it into two variables
You are getting date as 08/2019. Then to split it into month and year, you can use String function split(). For example,
String monthYear = "08/2019";
String[] arr = monthYear.split("/");
String month = arr[0]; //08
String year = arr[1]; //2019
One way is to use string.split:
String date = "08/2019";
String[] components = date.split("/");
String month = components[0];
String year = components[1];
If you have the day as well, you could parse a LocalDate from it:
String fullDate = "01/08/2019";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/uuuu");
LocalDate localDate = LocalDate.parse(fullDate, formatter);
localDate.getYear();
localDate.getMonth();

Possible to create a Java.time.LocalDate object from a String?

I have been trying to use the date.format(DateTimeFormatter formatter) method to format a list of date strings, where 'date' is a java.time.LocalDate object, for example. The problem is, I cannot find a straight-forward way to create a Year object from a string. For instance, if I have the string yearString = "90". I would like to create a Year object that is equal to this value, and then use the format method to output yearStringNew = "1990". The closest I see to a public constructor is the now() function which returns the current time.
I have also looked into creating a Calendar object and then creating a format-able date object there, but I can only create a Java.util.Date object – as opposed to an object in the Java.time package which could then ideally be formatted by the format function. Am I missing something here?
FYI I'm referencing the Java 8 SDK javadoc https://docs.oracle.com/javase/8/docs/api/
Thank you for your time.
EDIT: Per the request of another user, I have posted my code below; this is the closest I have come to accomplishing what I'm looking for:
//Module 3:
//Format Date Segments
package challenge245E;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
public class TestClass3 {
public static void main(String[] args) throws ParseException {
DateFormatter dateFormatter = new DateFormatter();
String myGroupedSlices [][] =
{
{"1990", "12", "06"},
{"12","6", "90"}
};
dateFormatter.formatDates(myGroupedSlices);
}
}
class DateFormatter {
public Date[][] formatDates(String[][] groupedDates) throws ParseException {
Date[][] formattedDates = new Date[groupedDates.length][3];
DateFormat yearFormat = new SimpleDateFormat("YYYY");
DateFormat monthFormat = new SimpleDateFormat("MM");
DateFormat dayFormat = new SimpleDateFormat("dd");
//iterate through each groupedSlices array
for (int i=0; i<groupedDates.length;i++) {
//Conditions
if (groupedDates[i][0].length()<3) {
//MDDYY format: if date[0].length < 3
//Re-arrange into YDM order
String m = groupedDates[i][0];
String y = groupedDates[i][2];
groupedDates[i][0] = y;
groupedDates[i][2] = m;
//convert dates to correct format
formattedDates[i][0] = yearFormat.parse(groupedDates[i][0]);
formattedDates[i][1] = monthFormat.parse(groupedDates[i][1]);
formattedDates[i][2] = dayFormat.parse(groupedDates[i][2]);
//testing if block
System.out.println("MDY Order: " + Arrays.toString(formattedDates[i]));
}
if (groupedDates[i][0].length()>3) {
//YYYYMMDD format: if date[0].length > 3
//convert dates to correct format
formattedDates[i][0] = yearFormat.parse(groupedDates[i][0]);
formattedDates[i][1] = monthFormat.parse(groupedDates[i][1]);
formattedDates[i][2] = dayFormat.parse(groupedDates[i][2]);
//testing if block
System.out.println("YMD Order: " + Arrays.toString(formattedDates[i]));
}
}
return formattedDates;
}
}
If I understand your requirement correctly, have a look at the LocalDate.parse() methods.
Example:
LocalDate date = LocalDate.parse("1990-01-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
int year = date.getYear(); // 1990
Parse Each Number Separately
It’s good to see you using the java.time framework rather than the troublesome old date-time classes. The old java.util.Date/.Calendar classes have been supplanted by the new framework.
The DateTimeFormatter class parses any two digit year as being in the 2000s. From class doc:
If the count of letters is two… will parse using the base value of 2000, resulting in a year within the range 2000 to 2099 inclusive.
To override this behavior, see this Answer by assylias. But that issue may be moot in your case. You already have the individual year, month, and date values isolated. So they need not be parsed together.
I suggest you convert each string into a integer. For the year, if less than 100 then add 1900.
String inputYear = "90";
String inputMonth = "12";
String inputDayOfMonth = "6";
int year = Integer.parseInt( inputYear );
int month = Integer.parseInt( inputMonth );
int dayOfMonth = Integer.parseInt( inputDayOfMonth );
if( year < 100 ) { // If two-digit year, assume the 1900s century. Even better: Never generate two-digit year text!
year = ( year + 1900 );
}
LocalDate localDate = LocalDate.of( year , month , dayOfMonth );
Create an Instance of class GregorianCalendar, set your date in that calendar and then use the method toZonedDateTime(). This will give you ZonedDateTime instance. form it you can use method LocalDate.from(TemporalAccessor temporal) method to get your LocalDate. Here how it might look:
//....
GregorianCalendar calendar = new GregorianCalendar();
// Set the deasired date in your calendar
LocalDate localDate = LocalDate.from(calendar.toZonedDateTime());
//...
import java.time.LocalDate;
public class DaysTilNextMonth {
public static void main(String[] args) {
//create an object for LocalDate class
LocalDate date = LocalDate.now();
//get today's day
int today = date.getDayOfMonth();
//get number of days in the current month
int numOfDaysInMonth = date.lengthOfMonth();
//compute the days left for next month
int dayForNextMonth = numOfDaysInMonth - today;
//display the result
System.out.println("The next month is: " + date.plusMonths(7).getMonth());
System.out.println("We have " + dayForNextMonth + " days left until first day of next month.");
}
}

Set date of calendar

Ok, so what I'm trying to do is to set the set the date of a calendar instance, and then return the week_of_year. I am doing so by using the Calendar.set() functio
public String weekInYearForm = "ww";
SimpleDateFormat formWIM = new SimpleDateFormat(weekInYearForm, Locale.US);
Calendar lc = Calendar.getInstance();
lc.set(Calendar.YEAR, lYear);
lc.set(Calendar.MONTH, lMonth);
lc.set(Calendar.DAY_OF_MONTH, lDay);
wiy = formWIM.format(lc.get(Calendar.WEEK_OF_YEAR));
To get the lYear, lMonth, and lDay values, I am passing a string in the format 04/26/2013 to through the following steps:
String[] arrDate = dateIn.split("/");
int lMonth = Integer.parseInt(arrDate[0]) - 1;
Log.d("SaveHandler", "Month is: " + lMonth);
int lDay = Integer.parseInt(arrDate[1]);
Log.d("SaveHandler", "Day is: " + lDay);
int lYear = Integer.parseInt(arrDate[2]);
Log.d("SaveHandler", "Year is: " + lYear);
The problem I am facing is that when I look at what is outputed to wiy, it is always 1. Upon some further debugging, I realized that the time is being left at epoch time, and not setting to the values I need.
I also tried using lc.set(lYear, lMonth, lDay), also to no avail. If anyone has any ideas, I would greatly appreciate them.
*EDIT: I did some debugging earlier and it is returning 1970 for the year and 0 for the month.
use
formWIM.format(lc.getTime());
instead of
formWIM.format(lc.get(Calendar.WEEK_OF_YEAR));
EDIT
You can parse your date (instead of dateIn.split( etc.)
SimpleDateFormat monthDayYear = new SimpleDateFormat("MM/dd/yyyy", Locale.US); //04/26/2013
Date date = monthDayYear.parse("04/26/2013");
and then format it
SimpleDateFormat formWIM = new SimpleDateFormat("ww", Locale.US);
formWIM.format(date);
This code is correct, the problem is in formWIM.format(...) or the battery of your motherboard clock is drained.

Categories

Resources