Wednesday 11 April 2018

Get week names in Java

In this post, you are going to learn.
a.   What is DateFormatSymbols API
b.   How to get an instance of DateFormatSymbols
c.   How to get all the week full & short names using DateFormatSybmols API.
d.   How to get localized week names?

What is DateFormatSymbols API?
'java.text.DateFormatSymbols' class encapsulates localized date-time formatting data. By using this class, you can get
a.   Names of the months,
b.   Short names of the months.
c.   The names and short names of the days of the week, and
         d. The time zone data

How to get an instance of DateFormatSymbols?
DateFormatSymbols class provides below constructors to get an instance of 'DateFormatSymbols' class.
DateFormatSymbols()
DateFormatSymbols(Locale locale)

How to get all the week full & short names using DateFormatSybmols API?
By calling 'getWeekdays' and 'getShortWeekdays' APIS, you can get the week full and short names.

Test.java
package com.sample.test;

import java.text.DateFormatSymbols;

public class Test {

 public static void main(String args[]) throws Exception {
  DateFormatSymbols dateFormatSymbols = new DateFormatSymbols();

  String[] weekDays = dateFormatSymbols.getWeekdays();

  System.out.println("Full Week Names:");
  for (String week : weekDays) {
   System.out.println(week);
  }

  System.out.println("\nShort Week Names: ");
  String[] shortWeekDays = dateFormatSymbols.getShortWeekdays();
  for (String week : shortWeekDays) {
   System.out.println(week);
  }

 }
}

Output
Full Week Names:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Short Week Names: 

Sun
Mon
Tue
Wed
Thu
Fri
Sat

How to get localized week names?
By defining the 'DateFormatSymbols' using specific locale, you can get locale specific names.

DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(Locale.GERMANY);


Test.java
package com.sample.test;

import java.text.DateFormatSymbols;
import java.util.Locale;

public class Test {

 public static void main(String args[]) throws Exception {
  DateFormatSymbols dateFormatSymbols = new DateFormatSymbols(Locale.GERMANY);

  String[] weekDays = dateFormatSymbols.getWeekdays();

  System.out.println("Full Week Names:");
  for (String week : weekDays) {
   System.out.println(week);
  }

  System.out.println("\nShort Week Names: ");
  String[] shortWeekDays = dateFormatSymbols.getShortWeekdays();
  for (String week : shortWeekDays) {
   System.out.println(week);
  }

 }
}


Output
Full Week Names:

Sonntag
Montag
Dienstag
Mittwoch
Donnerstag
Freitag
Samstag

Short Week Names: 

So
Mo
Di
Mi
Do
Fr
Sa






No comments:

Post a Comment