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();
Related
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.
I have successfully imported date column from excel to the java code. However, I am unable to change the date format from 17-Dec-2018 to 2018-12-17. Kindly help.
public void saveToDatabase(Vector dataHolder) throws ParseException {
System.out.println(dataHolder);
for(Iterator iterator = dataHolder.iterator();iterator.hasNext();) {
List list = (List) iterator.next();
fullName = list.get(0).toString();
idNumberString = list.get(1).toString();
//idNumber = Integer.parseInt ( idNumberString );
committee = list.get(2).toString();
amountString = list.get(3).toString();
//amount = Integer.parseInt ( amountString );
bosaFosa = list.get(4).toString();
purpose = list.get(5).toString();
paymentsType = list.get(6).toString();
supportingDocuments = list.get(7).toString();
entryDate = list.get(8).toString();
}
The code now after fetching data from excel column the month is in text as "Dec" that is "17-Dec-2018"
I expect the final output in string as "2018-12-17" so that I can store in MYSQL database as DATE Type.
java.time
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d-MMM-uuuu", Locale.ENGLISH);
String fullName = "Emmanuel Macron";
int idNumber = 42;
String entryDateString = "17-Dec-2018";
LocalDate entryDate = LocalDate.parse(entryDateString, dateFormatter);
PreparedStatement insertStatement = yourDbConnection.prepareStatement(
"insert into your_table (name, id, entry) values (?, ?, ?);");
insertStatement.setString(1, fullName);
insertStatement.setInt(2, idNumber);
insertStatement.setObject(3, entryDate);
int rowsInserted = insertStatement.executeUpdate();
The example is a bit simpler than yours, but should answer what you are asking about, so I trust the rest to you. I am using (and warmly recommending) java.time, the modern Java date and time API, for all date work in Java.
The steps involved for the date are:
Parse the date string into a LocalDate. LocalDate.parse(entryDateString, dateFormatter) does this. In the format pattern string, d-MMM-uuuu d means day of month in 1 or 2 digits, MMM means month abbreviation, and uuuu means 4 digit year. The month abbreviation is locale specific. Since I took Dec to be English, I have specified English locale for the formatter; please correct if your date strings are in some other language.
Pass the LocalDate to your PreparedStatement. insertStatement.setObject(3, entryDate); does this.
If you want to check that the first point worked as expected:
System.out.println("Entry date was parsed into " + entryDate);
Output:
Entry date was parsed into 2018-12-17
PS You may also want to check whether you can get the date from Excel in a different way. If you are using an older library such as Apache POI, I am afraid that the other option is an old-fashioned Date object, which you would then need to convert, so it’s a question whether it’s worth it.
Link: Oracle tutorial: Date Time explaining how to use java.time.
Your code is just simple. Here is code:
Parse string input.
String fromDate="17-Dec-2018";
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.ENGLISH);
LocalDate localDate = LocalDate.parse(fromDate, dateFormatter);
Generate string output.
String convertedDate = localDate.toString();
System.out.println(convertedDate);
Here DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.ENGLISH) is the input date format and locale.
Here is the imports:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
EDIT:
Please follow the answer of #Ole V.V. given above as it is a better solution than mine.
You will first have to convert the String data into Date object.
Example code:
String sDate1="31/12/1998";
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);
Then you can use SimpleDateFormat class to format date as you wish.
For more details on SimpleDateFormatter class, check this out
I am using Java 7 and fetching records for a week.For valid_from column I am subtracting -7 from current date below. The format of date in DB is 12-FEB-18. For valid_to column I am using sysdate. I am not getting correct valid_from date. Can anyone review this what is wrong here.
Format formatter = new SimpleDateFormat("dd-MMM-yy");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -7);
Date todate1 = cal.getTime();
Date startdate = ((DateFormat)formatter).parse(formatter.format(todate1));
System.out.println(todayWithZeroTime);
String sql_qry = "SELECT a.ACCOUNT_ID from tableName a where a.STATUS_TYPE_KEY='ACTIVE' "
+ "and a.VALID_FROM >"
+ startdate+ " and a.VALID_TO > sysdate";
How can I parse only Date here. Currently I am getting Tue Feb 13 00:00:00 GMT 2018. I want 13-FEB-18 which I can send as variable in where condition.
Please suggest
You are converting a Date to a String then back to a Date.
Then you are using this Date object in your query, so it's toString() method gets called and yields a String representation which is probably not the one you wanted.
Avoid the last conversion from String to Date and just use
String startdate = formatter.format(todate1);
Note that you also have to escape the date string with quotes :
String sql_qry = "SELECT a.ACCOUNT_ID from tableName a where "
+ "a.STATUS_TYPE_KEY='ACTIVE' "
+ "and a.VALID_FROM > '"
+ startdate+ "' and a.VALID_TO > sysdate";
Also consider having a look at Java time API and at How to use PreparedStatement
I'm trying to save a range of dates that will be filled in by the user, via 2 datepickers that were previously translated to Spanish.
The problem is that when I use strtotime() on the dates it takes the month as the day and vice versa.
Example:
I choose day 27 month 05 and year 2017, but the return value is an incorrect date format since the month is 27. If I choose day 01 month 05 year 2017 then it shows in the array as day 05 month 01 and year 2017.
Here are the functions I use to take the dates from the input texts, and to generate the range between the dates
function takedates() {
if(isset($_POST['repS'])){
$dateStart = $_POST['txtdesde'];
$dateEnd = $_POST['txthasta'];
$fechaArray = generafechas($dateStart,$dateEnd);
}
function generafechas($date1,$date2){
$fecharray = array();
if (is_string($date1) === true){
$deit1 = strftime("%d-%m-%Y",strtotime($date1));
}
if (is_string($date2) === true){
$date2 = strftime("%d-%m-%Y",strtotime($date2));
}
do {
$fecharray[] = date("m-d-Y", $date1);
$date1 = strtotime("+1 day", $date1);
} while($date1 <= $date2);
return $fecharray;
}
?>
My question is: How do i fill the array with the dates in the spanish date format?
PS: I've already used setLocale(LC_TIME,'es_ES') in the file where I'm using these functions, and the input shows the dates like this "dd/mm/yyyy"
strtotime does not take your locale into consideration when parsing the datetime string. If you use a date separated by slashes it is assumed to be American-style m/d/y. If you use a date separated by periods (or dashes if the year is four digits), it is assumed to be rest-of-the-world-style (d.m.y or d-m-Y). (Note that if you only use a two digit year and use dashes, PHP will try try to parse it as y-m-d.)
Instead of strtotime, you should use date-create-from-format / DateTime::createFromFormat to get a DateTime object, then build your date string from that.
UPDATE BASED ON COMMENTS: In order to get the output you want, you need to use the intl extension's IntlDateFormatter class to make the output.
To modify your code above (untested):
function generafechas($date1,$date2){
$fecharray = array();
if (is_string($date1) && is_string($date2)){
// These lines assume the input is formatted `day-month-year`,
// with 2-digit day and month, and 4-digit year.
$date1 = DateTime::createFromFormat('d-m-Y', $date1)
$date2 = DateTime::createFromFormat('d-m-Y', $date2)
} else {
throw new InvalidArgumentException('Must provide two date strings');
}
// Create the formatter
$formatter = IntlDateFormatter::create('es_ES', null, null, null, null, "d 'de' MMMM 'del' yyyy");
do {
// This line prints the first date in the format you chose above
$fecharray[] = $formatter->format($date1);
$date1->add(new DateInterval("P1D")); // `P1D` means "Duration of 1 Day" in the ISO 8601 standard
} while($date1 <= $date2);
return $fecharray;
}
If you provide the Locale along with the data, you can change what format string is used in createFromFormat as needed.
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);