1

I am new to java and i am making a weather app.

I am getting data from openweathermap server in JSON format. Below is the format

 "sys":{  
      "type":1,
      "id":7758,
      "message":0.2194,
      "country":"India",
      "sunrise":1410569741,
      "sunset":1410614119
   },

I want to extract sunrise and sunset from it but what i want is only time and not date. Below is my code

DateFormat df = DateFormat.getDateTimeInstance();

            String sunrise= df.format(new Date(json.getJSONObject("sys").getLong("sunrise")*1000).getTime());
            String sunset = df.format(new Date(json.getJSONObject("sys").getLong("sunset")*1000).getTime());

Problem with my code is that it is giving me both time and date and output is " Sep 13, 2014 6:25:41 AM" for sunrise. Similar is for sunset. ?

How shall i extract "6:25:41 AM" it? I only want time and not year/month/day

Sam
  • 1,237
  • 1
  • 16
  • 29

2 Answers2

3

You can do that by using the correct format: DateFormat.getTimeInstance().

NoDataFound
  • 11,381
  • 33
  • 59
2

try it this way

SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss a",Locale.ENGLISH);
System.out.println(df.format(new Date()));

Or this way

DateFormat ddf = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.ENGLISH);
System.out.println(ddf.format(new Date()));

Specify Locale it keeps you safe and Be carefull with the case of the letters for Example H means Hour of the day in 24-hour clock and h means hour of day in 12-hour clock. refer

SparkOn
  • 8,806
  • 4
  • 29
  • 34