Time stamp is not being written to Firebase database - java

I want to write a time stamp to the Firebase database so that I can later set what items can and can not be read from the Firebase database according to the time set. In my application I have a timpicker which the user uses to set the time, after which the set time is attached to the current date as shown below
Calendar c=Calendar.getInstance();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
String dateToday=df.format(c.getTime());
dateandtime=dateToday+time;
After which I convert dateandtime into a timestamp using the method below
try {
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date parsedDate=dateFormat.parse(dateandtime);
timestamp=new Timestamp(parsedDate.getTime());
}catch (Exception e){}
My class called Travel details for writing to the database is like this
......
private Timestamp pickuptime;
public Timestamp getPickuptime(){
return pickuptime;}
public void setPickuptime(Timestamp pickuptime){
this.pickuptime=pickuptime;
}
And this is how I write the time to the database in my main activity
Timestamp timestamp;
.............
d.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TravelDetails travelDetails=new TravelDetails() ;
travelDetails.setPickuptime(timestamp);
myRef.child(userID).push().setValue(
travelDetails);
Ali.push().setValue(travelDetails);
Instead of writing the time stamp to the database everything else from travel details class is written to the Firebase database except the time stamp. Kindly render assistance.

Firebase Realtime Database doesn't support writing Timestamp type values. It looks like you might be trying to use a Cloud Firestore Timestamp with Realtime Database. It doesn't work that way - they are different database systems. Timestamp objects can only be used with Cloud Firestore documents.
If you want to record a point in time with Realtime Database, you typically just use a number value for that.

Related

java-How should one pass a date value to MySQL?

I have a column field called StartDate in MySQL of Date datatype. In my application, I defined a way to show the current date onn my page like this.
String today = CoreUtil.parseDate(new Date());
This basically returns the date in YYYY-MM-DD format and stored it in a string which is fine.
Now, I would like to pass this value into a function that inserts the value to the column StartDate.
The function I declared is as follow:
public void insert_update(String nodeid,String ts,Date startdt,Date enddt,int enable)
I am calling this function and passing the value today to it like below:
fileFacade.insert_update(...,....,today,....,...);
Now I am not an expert in this date thingy and seeing it wouldn't allow me to pass the value as I defined it as Date parameter, how should I handle this issue?
Should I convert it back to Date format and pass the value or does MySQL allow insertion of string value into a Date datatype column?
I just want to store the value in my table in YYYY-MM-DD format.
edit:
My function:
public void insert_update(String nodeid,String ts,Date startdt,Date enddt,int enable){
try {
// UrlLink attr = em.find(UrlLink.class,n);
String sql="UPDATE urllink SET STARTDT="+startdt+",ENDDT="+enddt+",ENABLE="+enable+"WHERE URL='f0="+nodeid+"&ts="+ts + "'";
em.createNativeQuery(sql).executeUpdate();
}catch (Exception e) {
e.printStackTrace();
}
}
You should not try to convert String into a Date in order to insert it into a table. You can use date type as is using preparedStatement, e.g.:
Date date = new Date();
PreparedStatement pStmt = connection.prepareStatement("<query>");
pStmt.setDate(1, date);
Here's the javadoc.
Update
If the purpose here is to display the date in specified format then I would strongly recommend storing the date as DATE in MySQL in format it while querying. The decision of how we store the date should not be driven by how it needs to be displayed on Front End as we might need different date formats to be displayed across multiple User Interfaces.
Pass String date in method parameter instead of Date type and then format that date type like this:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
formatter.parse(date)

setText firebase TimeStamp to a TextView in Android

I'm reading data from cloud firestore one of which is a TimeStamp. So how I can set that TimeStamp to a TextView in an activity in SimpleDateFormat.
You can first turn the timeStamp to actual date format using a code like this:
private String getDate(long time) {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(time);
String date = DateFormat.format("dd-MM-yyyy", cal).toString();
return date;
}
Now you can set this date to textView using setText() method, using a code like below:
textView.setText(getDate(timestamp));
Here timeStamp can be the time stamp that you retrieve from your Firebase cloud Firestore.

How to store time in MySQL

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

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");
}

IBATIS TypeHandlerCallback getResult(ResultGetter getter) for converting EST time to UTC time

Thanks for the solution,but its not working out for me. I am dealing with a scenario where I am setting date(with time and timezone information) in the oracle database.I use Ibatis to extract this date and assign it to a java Date object. I implemented my TypeHandlerCallback as follows:
public class DateTimezoneTypeHandler implements TypeHandlerCallback {
public void setParameter(ParameterSetter setter, Object parameter)
throws SQLException
{ java.util.Date date = (java.util.Date) parameter; if ( date == null ) setter.setNull(Types.TIMESTAMP); else { Timestamp timestamp = new Timestamp(date.getTime()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); setter.setTimestamp(timestamp, calendar); } }
#Override public Object getResult(ResultGetter getter) throws SQLException {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
return getter.getTimestamp(calendar);
}
#Override public Object valueOf(String s) { throw new UnsupportedOperationException( "DateTimezoneTypeHandler.valueOf() is not supported."); } }
I have stored my date in the database in EST timezone and so getter has the date in EST time zone.Now when the date is read from the database,getResult function gets called but EST date is not not getting converted to UTC/GMT time zone. It is converting date having EST timezone to date having my local system timezone
**public Object getResult(ResultGetter getter) throws SQLException {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
return getter.getTimestamp(calendar);
}**
Following is my sql mapping:
I am not understanding what is the issue with this method implementation and why its not required functionality.
Please let me know if anyone has any suggestion/solution about this issue. I will really appreciate it.
The problem appears to be that you are not actually translating the time. Setting the timezone does not cause Calendar to convert the current value to the new timezone. Here is some example code that performs timezone translation GMT-5 (aka EST) to UTC. Note that I use Calendar.add and not Calendar.roll.
public static void main(String[] args)
{
Calendar calendar = Calendar.getInstance();
Date date;
int rawOffset;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("M/d hh:mm;ss a");
TimeZone timeZone;
date = calendar.getTime();
System.out.println(simpleDateFormat.format(date));
timeZone = TimeZone.getTimeZone("GMT-5");
rawOffset = timeZone.getRawOffset();
System.out.println(rawOffset);
calendar.add(Calendar.MILLISECOND, rawOffset);
date = calendar.getTime();
System.out.println(simpleDateFormat.format(date));
}
FWIW, our company has stopped storing Dates and Times as an Oracle timezone in the database. There is too much dependency on external configuration. Instead, we do the following:
Since asking for currentTimeMillis returns an absolute point in time, we create a TypeHandler for the Java Date class which stores the date/time in a NUMBER column in the database
Because reading millis-from-epoch is hard for humans, we add 2 functions to the database to convert from/to millis so that administrators can still write queries if they like to
The advantage of this is that you circumvent any "smart" time handling by anything outside the JVM. This is particularly handy when people enter a date in a foreign browser, pass that into your server app, and then passing it into the database.
In case you do want to store Dates in the database (sometimes you have to do these things), I personally can recommend Joda-Time for easier handling of dates, times, gregorian calendars and the likes.

Categories

Resources