-3

I have a String data like this.

String date="20170204";

the date format is - yyyymmdd

I have to set another integer variable according to the days of the week, i.e.

int day=1;

1 if Monday, 2 if Tuesday and so on. How can I do that in java 1.6?

Gholamali Irani
  • 4,391
  • 6
  • 28
  • 59
chichi
  • 1
  • 1
    You’d do yourself (and the community too) a favour if you search before asking. This question has been asked and answered before. – Ole V.V. Jan 11 '18 at 12:28
  • 1
    Tip: Rather than track and specify your day-of-week as a mere number 1-7, use the [`DayOfWeek`](https://docs.oracle.com/javase/9/docs/api/java/time/DayOfWeek.html) objects built into Java 8 and later. Example: [`DayOfWeek.TUESDAY`](https://docs.oracle.com/javase/9/docs/api/java/time/DayOfWeek.html#TUESDAY) – Basil Bourque Jan 11 '18 at 17:21

2 Answers2

2
String date_str="20180111";

DateTimeFormatter formatter  DateTimeFormatter.ofPattern("yyyyMMdd");

LocalDate date = LocalDate.parse(date_str, formatter);

int day = date.getDayOfWeek().getValue();

System.out.println(day);
Omayos
  • 21
  • 2
  • To use this in Java 6, get [ThreeTen Backport](http://www.threeten.org/threetenbp/) and add it to your coding project. – Ole V.V. Jan 11 '18 at 12:29
  • 2
    No need to specify the formatting pattern, as that pattern is pre-defined in this constant: [`DateTimeFormatter.BASIC_ISO_DATE`](https://docs.oracle.com/javase/9/docs/api/java/time/format/DateTimeFormatter.html#BASIC_ISO_DATE) – Basil Bourque Jan 11 '18 at 17:16
1
Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("yyyyMMdd").parse("20160204"));
int day = (6 + cal.get(Calendar.DAY_OF_WEEK)) % 7;

Obviously, you'll have to do with the imports and the exceptions.

SeverityOne
  • 2,476
  • 12
  • 25
  • Please don’t teach the young ones to use the long outdated `Calendar` class. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jan 11 '18 at 12:24
  • He asked specifically about Java 1.6. – SeverityOne Jan 12 '18 at 13:53
  • He did. So allow me to modify: Please don’t present the outdated `Calendar` class as the only or the first option and without any reservations. Better to get [ThreeTen Backport](http://www.threeten.org/threetenbp/), the backport of the modern API to Java 6 (and 7) and use it. – Ole V.V. Jan 12 '18 at 14:09