Ahmet Urun Ahmet Urun - 3 months ago 10
Android Question

Changing String type date to Day string

I'm using an API for my weather app and the JSON this API returns, gives me the 'Date' like that:

"date": "2016-08-20"
which is string type. But I want to write the day on screen like 'wednesday'. I look up for conversion on the internet but I couldn't find the solution for my case. Can anyone explain how to do that. Thanks in advance. By the way this is an android project.

rD. rD.
Answer

You simply need 2 SimpleDateFormatters,

  1. one to parse the String value of current date and get Date object from it.
  2. and second to get the week in String value from that Date Object.

Output

Saturday

Code

import java.util.*;
import java.text.*;

public class HelloWorld {
    public static void main(String[] args) throws ParseException {
        Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2016-08-20");
        String dayOfWeek = new SimpleDateFormat("EEEEE").format(date);
        System.out.println(dayOfWeek);
    }
}

OR - One Line Code - If we ignore Readability

import java.util.*;
import java.text.*;

public class HelloWorld {
    public static void main(String[] args) throws ParseException {
        System.out.println(new SimpleDateFormat("EEEEE").format(new SimpleDateFormat("yyyy-MM-dd").parse("2016-08-20")));
    }
}
Comments