How to? Insert current date from Android into mySQL database using Retrofit2 - java

Trying to insert Current date from android to mysql via Retrofit. The date is showing in the mysql database as 0000-00-00. I've read over multiple threads on SO on this topic and tried to apply the answers but so far I have not been successful. Please see the below code snippets for context.
PHP CODE:
<?php
include('conn.php');
$userId = $_POST['userId'];
$moodBefore = $_POST['moodBefore'];
$automaticThought = $_POST['automaticThought'];
$distortions = $_POST['distortions'];
$challengeThought = $_POST['challengeThought'];
$alternativeThought = $_POST['alternativeThought'];
$moodAfter = $_POST['moodAfter'];
$posted = $_POST['posted'];
$insert = "INSERT INTO Cbt ( userId, moodBefore, automaticThought, distortions, challengeThought, alternativeThought, moodAfter, posted) VALUES
('$userId','$moodBefore', '$automaticThought', '$distortions', '$challengeThought', '$alternativeThought', '$moodAfter', '$posted')";
$resultinsert = $conn -> query($insert);
if(!$resultinsert){
echo $conn->error;
}
?>
RETROFIT API CODE:
public interface Api {
#FormUrlEncoded
#POST("insert.php")
Call<ResponseBody> insertLog(
#Field("userId") int userId,
#Field("moodBefore") int moodBefore,
#Field("automaticThought") String automaticThought,
#Field("distortions") int distortions,
#Field("challengeThought") String challengeThought,
#Field("alternativeThought") String alternativeThought,
#Field("moodAfter") int moodAfter,
#Field("posted") String date
);
JAVA CODE:
String posted = new SimpleDateFormat("ddMMyyyy").format(new Date());
case R.id.nextBtnMoodPage:
if (hasSelected) {
Call<ResponseBody> call = RetrofitClient
.getInstance()
.getApi()
.insertLog(userId, moodBefore, automaticThoughtString, distortions, challengeThoughtString, alternativeThoughtString, moodAfter, posted);
call.enqueue(new Callback<ResponseBody>() {.....and so on
I would like the date to insert succesfully and not show 0000-00-00
If I could also make the date show as DD-MM-YYYY that would be even better.

This worked in the Java code, all other parts of the code stay the same
private Date currentDate() {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 0);
return cal.getTime();
}
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
String posted = dateFormat.format(currentDate());

Related

XPath Filter by Date

I need to filter the records by date through JAVA class:
public static final String DATE_TIME = "DateTime"
Date dateNow = setTimeToZero(Calendar.getInstance().getTime());
String date = DATE_TIME_FORMAT.format(dateNow);
Request request = table.createRequest();
DATE_FILTER = XPathFilter.newFilter("date-greater-than(" + Root_Table_DateField.format() + '$date')");
request.setXPathFilter(DATE_FILTER);
request.setXPathParameter(DATE_TIME, date);
RequestResult = reqResult = request.execute();
The field I am trying to access is define as DateTime, but I don't want the time now, so I set the time to zero, so I can filter for all field with date greater than dd-MM-yyyT00:00:00:000
But it return a predicate error: PredicateException: Invalid XPath expresion ./dateTime = 26-06-2020T00:00:00:000 - Unexpected 'T00:00:00.000'
Any clue?
Thank you
Try to add the date formatted like that (xs:date("2020-06-26Z")
date-greater-than(xs:date("2004-12-25-12:00"), (xs:date("2020-06-26Z"))
Reference: https://www.w3.org/TR/xpath-functions-31/

How do I convert Google's DateTime object to a long-type value?

I am trying to integrate a database with a web application that extracts event data from Google Calendar API which inputs the data into the database. The following code is identical to the Quickstart class provided by Google.
I basically want 'DateTime start' to be converted to 'long start'. I need the long value for SQL.
import com.google.api.client.util.DateTime;
// ...
DateTime now = new DateTime(System.currentTimeMillis());
Events events = service.events().list(calendarId)
.setTimeMin(now)
.setOrderBy("startTime")
.setSingleEvents(true)
.execute();
List<Event> items = events.getItems();
if (items.isEmpty()) {
System.out.println("No upcoming events found.");
} else {
System.out.println("Upcoming events");
for (Event event : items) {
DateTime start = event.getStart().getDateTime();
DateTime end = event.getEnd().getDateTime();
if (start == null) {
start = event.getStart().getDate();
}
System.out.printf("%s\n", start.toString());
Google has implemented the Rfc3339 parser in Google HTTP Client Library. You can try parsing it first and the use the DateTime.getValue() function to convert it into long.
You may also try using the DatetimeFormatter to format it to the way you want the value.
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.withZone(ZoneId.of("UTC"));
public void convertDatetime() {
String timeStamp = "2019-05-24T11:32:26.553955473Z";
DateTime dateTime = DateTime.parseRfc3339(timeStamp);
long millis = dateTime.getValue();
String result = formatter.format(new Date(millis).toInstant());

How to save multiple dates in Firebase database so that admin can keep track of orders on a particular date

final Date today = new Date();
Calendar nextYear = Calendar.getInstance();
nextYear.add(Calendar.YEAR, 1);
CalendarPickerView datePicker = findViewById(R.id.calendarPickerView);
datePicker.init(today, nextYear.getTime()).withSelectedDate(today);
datePicker.setOnDateSelectedListener(new CalendarPickerView.OnDateSelectedListener() {
#Override
public void onDateSelected(Date date) {
Calendar calselected = Calendar.getInstance();
calselected.setTime(date);
final String selectedDate = "" +
calselected.get(Calendar.DAY_OF_MONTH) + "/" +
(calselected.get(Calendar.MONTH) + 1) + "/" +
calselected.get(Calendar.YEAR);
String user_uid = mAuth.getCurrentUser().getUid();
final DatabaseReference current_user_db = mDatabase.child(user_uid);
alterupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
current_user_db.child("Altered date").setValue(selectedDate);
startActivity(new Intent(first_activity.this, second_activity.class));
}
});
}
});
I created calendar picker and saved the output in "Altered date" field. But when a user selects other date it is overriding the current date. So, what is the best option to save all the altered dates?
But when a user selects other date it is overriding the current date.
This is happening because you are calling set() method on the same reference. Since every node in a Firebase database is a Map and in case of Map, it replaces the old value with the new one.
So, what is the best option to save all the altered dates?
To solve this, I recommend you to use the push() method. For that, please change the followig line of code:
current_user_db.child("Altered date").setValue(selectedDate);
to
current_user_db.child("Altered date").push().setValue(selectedDate);

Azure DocumentDB - How can I fetch documents from the collection of particular date?

Each document contains date property shows when it is stored, so how can I fetch data stored on particular date or between two dates. What is the best way to do this. My implementation is based on Java. Thanks in advance.
I don't have the Java code, but you'll have to set up your collection to use Range indexing on the DateTime strings, then you'll be able to query for dates within a certain time range. The .NET code is to set up range indexing is:
DocumentCollection collection = new DocumentCollection { Id = "orders" };
collection.IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 });
await client.CreateDocumentCollectionAsync("/dbs/orderdb", collection);
See https://learn.microsoft.com/en-us/azure/documentdb/documentdb-working-with-dates#indexing-datetimes-for-range-queries and search for Range on this page https://learn.microsoft.com/en-us/azure/documentdb/documentdb-indexing-policies.
Just using Azure DocumentDB SDK for Java to query documents by _ts property. The document _ts property is as below.
_ts: This is a system generated property. It specifies the last updated timestamp of the resource. The value is a timestamp.
Here is my sample code as below. The _ts unit is second.
// Initialize a DocumentDb client.
String serviceEndpoint = "https://<your-documentdb-name>.documents.azure.com:443/";
String masterKey = "<your-documentdb-key>";
DocumentClient client = new DocumentClient(serviceEndpoint, masterKey, ConnectionPolicy.GetDefault(), ConsistencyLevel.Session);
// Get a collection link via collection id.
String collId = "<collection-Id>";
String query = String.format("SELECT * from ROOT r WHERE r.id = '%s'", dcId);
FeedOptions options = null;
List<DocumentCollection> dcs = client.queryCollections(dbLink, query, options).getQueryIterable().toList();
String collLink = dcs.size() >0 ? dcs.get(0).getSelfLink() : null;
// Generate a query string, see below.
.......
client.queryDocuments(collection.getSelfLink(), query, null);
A query string for fetching data stored on particular date:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = "2017-03-01";
long timestamp = sdf.parse(dateStr).getTime()/1000;
String query = String.format("select * from c where c._ts = %d", timestamp);
A query string for fetching data stored between two dates:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String startDateStr = "2017-03-01";
String endDateStr = "2017-03-31";
long tsStart = sdf.parse(startDateStr).getTime()/1000;
long tsEnd = sdf.parse(endDateStr).getTime()/1000;
String query = String.format("select * from c where c._ts >= %d and c._ts <= %d", tsStart, tsEnd);

Not able to create java calendar object in Node.js using java utilities in node.js

This is my piece of code to create java calendar object in Node.js using node-java module.
var java = require("java");
java.classpath.push("commons-lang3-3.1.jar");
java.classpath.push("commons-io.jar");
java.classpath.push("common-util.jar");
var vehId = java.newInstanceSync("java.lang.Integer", 922);
var lattitude = java.newInstanceSync("java.lang.Double", 8.6717136);
var longitude = java.newInstanceSync("java.lang.Double", 76.8168311);
var time= '';
var Calendar = java.newInstance("java.util.Calendar", function(err, result) {
if(err) {
console.log('Error: '+err);
return;
}
else {
console.log("Result: "+result);
time = Calendar.getInstance();
}
});
var args = {
vehicleId : vehId,
lat : lattitude,
lan : longitude,
packetTime : time
};
console.log(args);
This is the error got when tried to execute the program.
Error: Could not find method "java.util.Calendar()" on class "class java.util.Calendar". No methods with that name.
Couldn't create calendar object using java.newInstance() or java.newInstanceSync() functions.
Try this.
var Calendar = java.newInstanceSync("java.util.GregorianCalendar");
It will create a default GregorianCalendar using the current time in the default time zone.

Categories

Resources