Ehsan
Ehsan

Reputation: 2781

Can't Set correct date and time to Calendar

I am getting date time as String in this format from the server:2017-11-15 16:27:02

I want to set Calendar with this time so I Do something like this:

 String[] dateTime = response.body().getUser().getUserSessionExpire().split(" ");
 String[] date = dateTime[0].split("-");
 String[] time = dateTime[1].split(":");
 Log.i("TIMMEE", "Received TIME: " + response.body().getUser().getUserSessionExpire());

 int month = Integer.parseInt(date[1]);
 int day = Integer.parseInt(date[2]);
 Calendar calendar = Calendar.getInstance();
 calendar.set(Calendar.YEAR, Integer.parseInt(date[0]));
 calendar.set(Calendar.MONTH, month);
 calendar.set(Calendar.DAY_OF_MONTH, day);
 calendar.set(Calendar.HOUR, Integer.parseInt(time[0]));
 calendar.set(Calendar.MINUTE, Integer.parseInt(time[1]));
 calendar.set(Calendar.SECOND, Integer.parseInt(time[2]));

For example, if I get

2017-11-15 16:27:02

Calendar will set for :

2017-12-15 16:27:02 Or 2017-11-16 16:27:02

Actually, Month or Day will change! What is the problem?

Thankyou for your answers.

Upvotes: 1

Views: 194

Answers (1)

SpiritCrusher
SpiritCrusher

Reputation: 21043

You do not need to split the date . SimpleDateFormat is responsible for formating . So you can parse the date and get Date object from it . See code below and read the SimpleDateFormat(linked above).

Calendar calendar=Calendar.getInstance();
    SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd H:m:s", Locale.getDefault());
    try {
       Date d = DATE_FORMAT.parse("2017-11-15 16:27:02");
        calendar.setTime(d);// Use this calender 
    } catch (ParseException e) {
        e.printStackTrace();
    }

Upvotes: 2

Related Questions