How to store time in MySQL - java

I have an html page having a form with input type="time".
This time is in 12 hr format by default.
The user will select the time and it should get stored in the MYSQL database.
In my database, I have created a table with the field called "bookingTime" and its datatype is TIME.
I am trying to write the java code to store the time in the database.
The problem is, when I select the time (for Ex. 03.30 PM) on the HTML page, it is being received in the backend as "1970-01-01T20:30:00.000Z".
I am not able to parse this and store the actual time(which is 15:30:00) in the MYSQL database.
Can someone provide me the java code to do this?

You can use a Calendar variable, so you can create a new Calendar and set the time.
After that, use a PreparedStatement to set the time as String, using SimpleDateFormat("HH:mm:ss")
Calendar myCalendar = Calendar.getInstance();
myCalendar.set(Calendar.HOUR, hour);
myCalendar.set(Calendar.MINUTE, minute);
myCalendar.set(Calendar.SECOND, second);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss" );
String time = sdf.format( myCalendar.getTime() );
...
ps.setString("myTimeField", time);

Here I am using your String "1970-01-01T20:30:00.000Z", but it should be replaced with your expected content from that form
DateFormat formatFromHtml = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateFormat formatterToMySQL = new SimpleDateFormat("H:mm:ss");
Date result = formatFromHtml.parse("1970-01-01T20:30:00.000Z");
String validForTimeInMysql = formatterToMySQL.format(result);
After that, in validForTimeInMysql you get a String that can be added to MySQL

Related

How to Convert solr date to javascript date?

i am having the time in "2016-11-17T09:22:24Z" and i need to convert it into
"2016-11-1709:22:24".Just need to remove T and Z from solr Date and i need to add 330 minutes to that date and display it
First we can construct a javascript date object from the string and then you can convert it into correct format:
var dt = new Date('2016-11-17T09:22:24Z')
var formattedDate = dt.toISOString().substring(0, 19).replace('T', '')
console.log(formattedDate) should log 2016-11-1709:22:24
Or in one line:
new Date('2016-11-17T09:22:24Z').toISOString().substring(0, 19).replace('T', '')
will render: 2016-11-1709:22:24
Some more good discussions here: Convert javascript to date object to mysql date format (YYYY-MM-DD)
var userdate = new Date("2009-1-1T8:00:00Z");
var timezone = userdate.getTimezoneOffset();
var serverdate = new Date(userdate.setMinutes(userdate.getMinutes()+parseInt(timezone)));
This will give you the proper UTC Date and Time.
It's because the getTimezoneOffset() will give you the timezone difference in minutes. I recommend you that not to use toISOString() because the output will be in the string Hence in future you will not able to manipulate the date

Adding 30 days on the value from JDateChooser using Java netbeans

hi all I am working on a form using JDateChooser I want to get the value of date inputted by the user. Is there any ways that after storing the value of date in a variable can I add 30 days from the inputted date? This is my code in passing the date to a string variable:
String dates =((JTextField)date.getDateEditor().getUiComponent()).getText();
my problem is how can I pass the date into a variable where i can be able to add an additional 30 days on it?
please help me really need this for my project .
To manipulate a String with a date value, you first need to convert to a Date using SimpleDateFormat, then you can perform manipulation using a Calendar.
SimpleDateFormat datefmt = new SimpleDateFormat("MM/dd/yyyy"); // Or format you're using
Date date = datefmt.parse(dates);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, 30); // Add 30 days
Date futureDate = cal.getTime();
If you need value for insertion into a database, you will of course use PreparedStatement, so you'll need a Timestamp instead:
// From Date
Timestamp futureTimestamp = new Timestamp(futureDate.getTime());
// Directly from Calendar
Timestamp futureTimestamp = new Timestamp(cal.getTimeInMillis());

DateTime convertion in java

I have a date get saved in the database in IST format.
Date nowDate = new Date();
Date dateBefore = new Date(nowDate.getTime() - 7* 24 * 3600 * 1000);
System.out.println("Datebefore-->"+dateBefore);
Here in the above code dateBefore is get saved in the database.
From the database I am taking the data long value and I have to convert this into Google DateTime
Date dateBefore12 = new Date(longvalue);
com.google.api.client.util.DateTime dd = new DateTime(dateBefore12, TimeZone.getTimeZone("UTC"));
Now for example the output will be in the 2014-07-17T05:23:28.857Z which I have to pass to the Google You tube API.
Now from the response I will take Google DateTime, let say 2014-07-17T05:23:28.857Z which I have to increment the 1 minute and then convert it into long and save into db.
Convert the google DateTime to long.
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat f = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String input = dd.toString();
GregorianCalendar cal = new GregorianCalendar(utc);
cal.setTime(f.parse(input));
cal.add(Calendar.MINUTE,1);
Date time = cal.getTime();
long longvalue1 =cal.getTimeInMillis();
Now I will saved the data and try to retrieve it. It gives me back 2014-07-16T23:54:28.857Z.
But I need the save date value which I have increment by one minute in the format of google DateTime.
SimpleDateFormat also uses a time zone, due to an internal Calendar object, which defaults to the local time zone. If you don't want to use that default time zone, then before you call the format's parse() method, you should call setTimeZone() on it:
f.setTimeZone(utc);

sql query to validate the form which has from and to date and it should allow only for current date not the next day

I have a form where have to enter from and to date in date picker , but while saving the data the from date and to date should be for the current date. And if i enter to date as tomorrows date it should not allow to save the date.Kindly let me know as how to do this in mysql . May I know what is the correct way to achieve my objective?
Not quite sure on what you are trying to achieve...
In general, if you have to validate a form you should it in your java code before inserting stuffs into the DB.
You can check ad a DB level using a trigger (BEFORE INSERT) or a constraint (you can use the constraint anyway to ensure the data integrity) but I believe that a check in Java is easier to maintain.
another reference for java 8 users:
if you are referring to:
http://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/DatePicker.html
then you just need to play with:
http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
final DatePicker datePicker = new DatePicker(); //assuming this is your DatePicker on the form
LocalDate date = datePicker.getValue();
//comparing with current date (LocalDate.now())
if(date.compareTo(LocalDate.now())!=0)
{
JOptionPane.showMessageDialog(null, "Invalid input date!");
}
else{
//save to DB..
}
note: I haven't tried to run this though..
This way you can do it..
It takes date from screen.. (You have to parse date from string)
It takes today's date of midnight
It takes tomorrow's date of midnight
Check that screen's date should be between today's midnight and tomorrow's midnight
Date date_from_screen = new Date();
Date today = new Date();
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
Date tomorrow = new Date(today.getTime() + 1 * 24 * 60 * 60 * 1000);
tomorrow.setHours(0);
tomorrow.setMinutes(0);
tomorrow.setSeconds(0);
if((date_from_screen.getTime() >= today.getTime()) && (date_from_screen.getTime() <= tomorrow.getTime()))
{
System.out.println("valid date");
}
else
{
System.out.println("invalide date");
}

Can't write time to database, only date. time gets ignored

I am trying to insert date and time but only the date goes through. when I check the database the time is always 00:00
public void suspendPart(String partId, String startDate,
String reasonCode, String endDate) throws DAOException {
System.out.println("original date: "+startDate); //output: original date: 04/01/2013 08:42
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Map<String, Object> params = new HashMap<String, Object>();
params.put("p_id", Integer.parseInt(partId));
Date dateTest = DAOUtils.parseDate(startDate, format);
System.out.println("date after format " +dateTest); // output: date after format Fri Jan 04 08:42:00 GMT 2013
params.put("p_start_date", dateTest);
parts_package_add_part.execute(params);
}
I managed to make it work once but I don't know how. by the time I checked the database and saw a row with proper time, I had already messed with the code so it was lost.
Can anyone see what I'm doing wrong?
Edit: sp declaration
parts_package_add_part = SpringStoredProcedure
.getStoredProcedureCompiled(getJdbcTemplate(), false,
"parts_package.add_part",
new SqlParameter("part_id", OracleTypes.NUMBER),
new SqlParameter("p_start_date", OracleTypes.DATE));
Edit: I can't change the database. well not easily at least. I would need to get PLSQL developer to do it and that will take days
I recently had a simular problem. My solution was to use TIMESTAMP as oracle data type in the database table and the java.sql.Timestamp class in java. This matched fine...
Using Timestamp could help. What is the datatype used to store your date in db? May be it is a Date type. If you convert that to Timestame/DateTime it could help.
Hi try using timestamp datatype in your database table and also from your java code use java.sql.Timestamp it will store data and time both for you
Thanks

Categories

Resources