Passing date and time JSON PHP format to Java

4

I have this JSON that comes from a PHP :

[{"id":101,"date":{"timezone":{"name":"Europe\/Berlin","location": {"country_code":"DE","latitude":52.5,"longitude":13.36666,"comments":"most locations"}},"offset":7200,"timestamp":1471212000},

How can I pass this date in JSON format to a Java date? Extract the fields I know how to do, what I do not know is how to use them.

And if it's one hour:

"time":{"timezone":{"name":"Europe\/Berlin","location":{"country_code":"DE","latitude":52.5,"longitude":13.36666,"comments":"most locations"}},"offset":3600,"timestamp":36000}

In the latter case the date gives me the same, the important thing is to pass the time to Java.

After I get the date in Java, what can I do to show only the date in TextView ? And show only the time in a TextView ?

    
asked by Red 24.04.2016 в 15:25
source

3 answers

2

To show the date in a TextView, if you have the date in a variable type String or Date, you can add it in this way:

Assuming a TextView within our layout:

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

The reference is obtained and the text is added:

//A partir del id del TextView.
TextView textView = (TextView)findViewById(R.id.textView);
//Agregas el texto, el cual puede ser una variable Date o String.
textView.setText(mifecha);

With respect to changing the format, you can decide on the format, for example if you want a format "yyyy-MM-dd hh: mm: ss":

//Seguramente obtendras un string del valor de timestamp, hay que convertirlo a long.
String miJSONTimeStamp = "1471212000";
Long miTimeStamp = Long.parseLong(miJSONTimeStamp);    

//Define formato de salida deseado.
String formatoDeseado = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat formatter = new SimpleDateFormat(formatoDeseado);

//Crea objeto para convertir millisegundos a fecha.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(miTimeStamp);

//aplica formato
String fechaconFormat  = formatter.format(calendar.getTime());

//agrega texto con formato dentro del textView.
textView.setText(fechaconFormat);

The result will be:

If you want only the date simply define it within the SimpleDateFormat

 String formatoDeseado = "yyyy-MM-dd";
 SimpleDateFormat formatter = new SimpleDateFormat(formatoDeseado);

If you want only the time, you also define it within the SimpleDateFormat

 String formatoDeseado = "HH:mm:ss";
 SimpleDateFormat formatter = new SimpleDateFormat(formatoDeseado);

Check what format you want:

link

    
answered by 24.04.2016 в 18:32
0

Well, I have already implemented it but it fails:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String json = "[{'date':{'timestamp':1144015200}, 'time':{'timestamp':36000}}]";
    long dateTimestamp = 0;
    long timeTimestamp = 0;


    try {
        JSONArray jsonArray = new JSONArray(json);
        JSONObject jsonObject = jsonArray.getJSONObject(0);

        JSONObject jsonObjectDate = jsonObject.getJSONObject("date");
        JSONObject jsonObjectTime =  jsonObject.getJSONObject("time");

        dateTimestamp = Long.parseLong(jsonObjectDate.getString("timestamp"));
        timeTimestamp = Long.parseLong(jsonObjectTime.getString("timestamp"));

        Log.i("Resultado", "date = " + dateTimestamp);
        Log.i("Resultado", "time = " + timeTimestamp);

    } catch (JSONException e) {
        e.printStackTrace();
    }

    String fechaTimestamp = String.valueOf(dateTimestamp);
    String formatoFecha = "d-MM-yyyy";
    SimpleDateFormat formatter = new SimpleDateFormat(formatoFecha);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(dateTimestamp);

    String fechaConFormato = formatter.format(calendar.getTime());
    Log.i("Resultado", fechaConFormato);

    String formatoHora = "k:m:s";
    formatter = new SimpleDateFormat(formatoHora);

    calendar.setTimeInMillis(timeTimestamp);

    String horaConFormato = formatter.format(calendar.getTime());
    Log.i("Resultado", horaConFormato);
}

}

The result is: date = 1144015200 time = 36000 01-14-1970 24: 0: 36

The date that would have to leave is: 03-04-2006 and the hour 11:00:00.

Can you think of something? The timestamp is generated by the server, I do not know if it could be generating them wrong. Another option would be to send a json package with the date and time as String, but then how could you encapsulate it in a Java date object.

I've done this test:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String strFecha = "03-04-2006";
    Calendar calendar = GregorianCalendar.getInstance();
    Date fecha = calendar.getTime();
    SimpleDateFormat formatoDeFecha = new SimpleDateFormat("dd/MM/yyyy");
    Log.i("resultado", formatoDeFecha.format(fecha));
}

}

But the result is: 05/01/2016.

I'm a little lost with this: (

Thanks for any help you can give me.

Greetings

    
answered by 02.05.2016 в 10:47
0
  

Warning: I see that the comments have been deleted, if it comes to this   question to apply it to Android this is not your answer as the   Original question to mutated.

In this link you can see some data to do ect verifications. link

link

import java.util.Date;
import java.sql.Timestamp;

public static void main (String[] args) throws java.lang.Exception {


   Timestamp stamp = new Timestamp(1471212000);
   Date date_f = new Date(stamp.getTime() * 1000L);

        System.out.println(date_f.toString());
        System.out.println(date_f);
}

The toString method applies the default time zone of the JVM, for java.util.Data this does not have time for the zone.

With java.time you can manage time in several ways:

.

import java.time.ZoneOffset;
import java.time.OffsetDateTime;
import java.time.Instant;

import java.time.ZoneId;
import java.time.ZonedDateTime;

import java.time.format.DateTimeFormatter;

public static void main (String[] args) throws java.lang.Exception {

    Instant instant                  = Instant.now();
    ZoneOffset zone_offset           = ZoneOffset.of( "+01:00" );
    OffsetDateTime offeset_date_time = OffsetDateTime.ofInstant( instant , zone_offset );       

    System.out.println(instant.toString());
    System.out.println(offeset_date_time.toString());

    ZoneId zone_id = ZoneId.of( "America/Los_Angeles" ); // <- Mirar shortIds link
    ZonedDateTime zoned_date_time = ZonedDateTime.ofInstant( instant , zone_id );

    System.out.println(zoned_date_time.toString());

    //Formato ejemplo

    DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_DATE_TIME; // <-- Mirar link DateTimeFormatter predefined
    String output = formatterOutput.format(zoned_date_time);
}

shortdIds Link

DateTimeFormatter predefined Link

link

Update:

I had already commented that this could happen, in a comment in Elenasys' answer, but I'll put it back as an update (due to your new question, which of course leaves a comment, explaining how to update your question).

  

The result is: date = 1144015200 time = 36000 14-01-1970 24: 0: 36

The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds .... 1471212000 seconds - > * 1000L - > setTimeInMillis , I hope you understand what I want to say, if you do not apply 1000 to setTimeInMillis will treat the data in the same way and not having 1000 because the dates are different.

try the following, in places where you use setTimeInMillis(dateTimestamp) :

.setTimeInMillis(dateTimestamp * 1000L);
    
answered by 24.04.2016 в 17:30