get DateTime from mysql database into android sqlite - mysql

I want to get data from mysql and store it in an android app. I could not find a Date or Time field in android. I have to save it to sqlite database and keep it for the next app update. In the next update I get the sqlite Date and check against the mysql database find out if there is a new post or not.
How can i get the data in the below loop?
for (int i = 0; i <count; i++)
{
JSONObject json_data = jArray.getJSONObject(i);
temp +=
"Name : " + json_data.getString("name")+ "\n"+
"Lastname : " + json_data.getString("lastname")+
date : " + //the DateTime "\n";
}

Although SQLite saves date as text or numeric, you can achieve features of mysql date/datetime in SQLite as well (indirectly).
Get datetime as per UTC timezone and save into SQLite db in milliseconds (long value) . SQLite takes numeric datatypes
Sample code:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = format.parse(text);
long millis = date.getTime();
//your code - save datetime in milliseconds in SQLite numeric field
Indirectly you can avail all features of datetime in SQLite that mysql datetime has.

Related

Neo4j Date conversion and comparison?

I was working with MS access database.MY datetime is now like "05-03-2016 14:55:20" .I need to convert it into datetime format in neo4j.1.How to do it ? 2.After conversion I need to use date filter i.e I want to find all nodes created between 2 dates.How to do it ?
If Neo4j is pulling data from Access query, construct field in query that calculates date to a string that Neo4j can then convert to date with its DateTime function.
Format([fieldname], "yyyy/mm/dd hh:nn:ss")
You can use the APOC function apoc.date.parse() to convert your MS Access datetime string into the number of seconds from the UNIX epoch, and then construct a neo4j datetime from that value. For example, this will return a neo4j datetime that represents your sample time string:
RETURN datetime({
epochSeconds: apoc.date.parse('05-03-2016 14:55:20', 's', 'MM-dd-yyyy HH:mm:ss')
})
A neo4j temporal type can only be compared directly to the same type. For instance, to compare a datetime X to a date Y, you can convert X to a date before doing the comparison. The following sample query will return true:
WITH
datetime({
epochSeconds: apoc.date.parse('05-03-2016 14:55:20', 's', 'MM-dd-yyyy HH:mm:ss')
}) AS X,
date('2016-05-04') AS Y
RETURN date({date: X}) <= Y

Dates are incorrect with json passed like "jsonObject.toString()"

I have a graph component written in javascript using the canvas. You can update its values if you pass it a valid json array, of dates, coupled with prices of that date (stock trading candlesticks).
The jsonArray I try to populate on this call usually comes from creating new dates in js - but is there a way to send my jsonArray down the wire (from Primefaces) in such a way that the dates get interpreted as dates?
When I use
PrimeFaces.current().executeScript("myFunction(" + jsonObject.toString() + ")");
Dates that come down the wire are becoming long looking numbers which I guess are the number of milliseconds since 1970. What can I do to send this (rather large) jsonarray and have its dates interpreted as dates? (they fail on the date.getMonth() call, because they are numbers instead of dates).
When creating the jsonArray on the server side, I do the following, which looks wrong because getTime() returns a long. So how would dates be properly handled here?
json.addProperty("date", data.getKey().getTs().getTime());
The function getting called with the long values as dates was the following. As Ultimater suggested, pass this object through new Date() - which should work for a date object - as well as a long, so no harm done!
dateToString(date, multiline) {
if(date === null)
return;
// Added this
date = new Date(date);
var datestr = date.getMonth() + " " + date.getDay() + ", " + date.getFullYear();

Python 2.7, MySQL, JSON, & DateTime - How can I remove the T between the Date and Time in the timestamp field?

I have a MySQL database with a few tables. I wrote a python script to dump some of the tables data into a JSON file. I am a bit confused with dumping the date and time stamp.
Here is the code sample, conversion.py:
import MySQLdb
import json
import collections
from datetime import date, datetime
#connect to database
conn = MySQLdb.connect(host= "localhost", user="root", passwd="root", db="testdb")
#Fetch rows
sql = "SELECT * from offices"
cursor = conn.cursor()
cursor.execute(sql)
rows = cursor.fetchall()
data = []
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.isoformat()
raise TypeError ("Type %s not serializable" % type(obj))
for row in rows:
d = collections.OrderedDict()
d['officeCode'] = row[0]
d['city'] = row[1]
d['phone'] = row[2]
d['eff_date'] = row[3]
d['lastupdatedby'] = row[4]
d['state'] = row[5]
d['country'] = row[6]
d['postalcode'] = row[7]
d['territory'] = row[8]
data.append(d)
with open('data.json', 'w') as outfile:
json.dump(data, outfile, default=json_serial)
conn.close()
When I execute this code, a JSON file is created which is fine. I have a problem with two fields, eff_date which is a date type in database and lastupdatedby is a timestamp type in the database.
"eff_date": "2015-09-23"
"lastupdatedby": "2016-08019T08:13:53"
So, in my JSON file, eff_time is created fine but lastupdatedby is getting a T in middle of date and time as shown above. But, in my actual database there is no T between the date and time. I would like to get rid of that T because I am planning to dump this file into a different database and I don't think it will accept that format.
Any help will be much appreciated.
The T between the date and time is per the ISO 8601 format.
And that's format returned by the datetime.isoformat function, found in the code here:
return obj.isoformat()
(That happens to be the format that Javascript is expecting.)
If we want to return a string different format, we probably need to use a different function, e.g. strftime function in place of isoformat.
If isoformat is working for the date objects, leave that alone. Just do the strftime for a datetime object.
The format string "%Y-%m-%d %H:%M:%S" might suit your needs.
https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Inserting date in Mysql (codename one)

I want to insert a Date object in mysql database, which has a Date type in the database as well. I am having problems inserting the date .
I have tried this code, but it seems codename one have a problem with it:
dateString s;
s = date.getCurrentMonth() + "/" + date.getCurrentDay() + "/" + date.getCurrentYear();
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = (Date) formatter.parse(s);
Please can you tell me how to do it ?
You don't need to format it. Just use this SQL Date Object instead of Date object from java.util package.
import java.sql.Date
// Creating a date object.
Date date = new Date();
In a database, make sure the data type of attribute 'date' is selected as "Date" also, not VarChar. Simply pass this sql package Date object into the database through query. :) It will save the date in a format.

How to extract time from mysql time then load to datetimepicker with custom hh:mm:ss

I have a datetimepicker with custom format hh:mm:ss tt
I want to fetch the data from mysql with time data type using MySqlDataReader
The date is fine using
dtpmyDate.Value = reader.GetDateTime("dateposted").ToShortDateString
How about the time?
this one resolve me
getTime = reader.GetString(reader.GetOrdinal("timeposted")).ToString
Dim today As DateTime = DateTime.Now.Date
Dim timeToSet As New TimeSpan(20, 20, 30)
dtpmyTime.Value = today + " " + getTime
dtpmyTime is datetimepicker with custom format is hh:mm:ss
with ShowUpDown = true
I only wants the time value since the date will be updating current date to the database when the record is saved..
Thank you everyone. this site is more practicable place to query my problem that will solve immediately.
When you assign the .Value of a DateTimePicker, you need to include the date part as well as the time part. If the MySQL column has a type of TIME, then you should read that as a TimeSpan and add it to an appropriate date.
Dim today As DateTime = DateTime.Now.Date
Dim timeToSet As New TimeSpan(20, 20, 30)
DateTimePicker1.Value = today + timeToSet