1

I am new to android and I am stuck at one place. I wanted to fetch the date from mysql database and display it in android app.

The code for android application

 try {
JSONArray data = response.getJSONArray("std");
String result[]=new String[data.length()];
for (int i = 0; i < data.length(); i++)
{
    JSONObject obj = data.getJSONObject(i);
    name = obj.getString("Name");
    fromdate=obj.getString("From");
    todate = obj.getString("To");
    DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
    Calendar cal=Calendar.getInstance();
    Date fd=formatter.parse(fromdate);
   cal.setTime(fd);
   from1=cal.getTimeInMillis();
   Date td=formatter.parse(todate);
   cal.setTime(td);
   to1=cal.getTimeInMillis();              
   date= DateUtils.formatDateRange( Main2Activity.this, from1, to1,  
     DateUtils.FORMAT_SHOW_YEAR );
   result[i]=""+name+"\n"+date;
  }

JSON FILE

<?php
$result=mysqli_query($link,"select * from oTrip");
$data=array();
$rows=mysqli_num_rows($result);
while($rec=mysqli_fetch_assoc($result))
{
$data[]=$rec;
}
header('Content-Type: application/json');
echo json_encode(array("std" =>$data));
?>

And the output is

enter image description here

Please help out with this!! Thank You.

3 Answers3

0

Change "dd-MM-yyyy" to "dd/MM/yyyy"

  • While this code snippet may be the solution, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-‌​code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – yivi Dec 21 '17 at 11:29
0

You can do this,

 fromdate=obj.getLong("From");
 SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd/MM/yyyy");
     sdf.format(new Date(fromdate));
Ritu Suman Mohanty
  • 734
  • 1
  • 6
  • 15
0

Use this:

 JSONObject obj = data.getJSONObject(i);
 name = obj.getString("Name");
 fromdate=obj.getString("From");
 todate = obj.getString("To");
 DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
 Date fd=formatter.parse(fromdate);
 Date td=formatter.parse(todate);
 DateFormat newFormatter = new SimpleDateFormat("dd-MM-yyyy");
 String newFromdate = newFormatter.format(fd);
 String newTodate = newFormatter.format(td);
 date = newFromdate + " - " + newTodate;
 result[i]=""+name+"\n"+date;

You have to parse date in given JSON format and then change that parsed date into new format using another formatter.

You can use one-liners as:

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
DateFormat newFormatter = new SimpleDateFormat("dd-MM-yyyy");
fromdate = newFormatter.format(formatter.parse(fromdate));
todate = newFormatter.format(formatter.parse(todate));
global_warming
  • 833
  • 1
  • 7
  • 11