Reputation: 1808
I have date time information in this format:
String reportDate="2012-04-19 12:32:24";
I want to have as output day of the week (Thursday or 4 as result anyway is good). How to achieve this?
Thanks
Upvotes: 2
Views: 1487
Reputation: 78995
java.time
In March 2014, Java 8 introduced the modern, java.time
date-time API which supplanted the error-prone legacy, java.util
date-time API.
Parse the given date-time string into LocalDateTime
instances by using a DateTimeFormatter
with the corresponding pattern. Then, get the desired values from the resulting LocalDateTime
object.
Demo:
public class Main {
public static void main(String[] args) {
String reportDate = "2012-04-19 12:32:24";
DateTimeFormatter parsingPattern = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(reportDate, parsingPattern);
System.out.println(ldt.getDayOfWeek()); // THURSDAY
System.out.println(ldt.getDayOfWeek().getValue()); // 4
// Get the textual representation of the enum constant
System.out.println(ldt.getDayOfWeek()
.getDisplayName(TextStyle.FULL, Locale.ENGLISH));
System.out.println(ldt.getDayOfWeek()
.getDisplayName(TextStyle.FULL, Locale.forLanguageTag("hi-IN"))); // Hindi
System.out.println(ldt.getDayOfWeek()
.getDisplayName(TextStyle.FULL, Locale.forLanguageTag("bn-BD"))); // Bangla
// Alternatively,
System.out.println(ldt.format(DateTimeFormatter.ofPattern("EEEE", Locale.ENGLISH)));
}
}
Output:
THURSDAY
4
Thursday
गुरुवार
বৃহস্পতিবার
Thursday
Note that DayOfWeek#THURSDAY
is an enum
constant and you can get the textual representation using DayOfWeek#getDisplayName
.
Learn more about the modern Date-Time API from Trail: Date Time.
Upvotes: 2
Reputation: 9134
Try,
System.out.println(new SimpleDateFormat("E").format(new SimpleDateFormat("yyyy-MM-dd").parse(reportDate)));
System.out.println(new SimpleDateFormat("F").format(new SimpleDateFormat("yyyy-MM-dd").parse(reportDate)));
Upvotes: -1
Reputation:
Use the Calendar
after parsing the string:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
Date d = sdf.parse(reportDate);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
return cal.get(Calendar.DAY_OF_WEEK);
Upvotes: 5
Reputation: 2234
Use the SimpleDateFormat to parse the String
then you have a Date
object an can get the day of the week.
Upvotes: 1
Reputation: 52185
Parse your date to an actual Date
Object and then pass it to a Calendar Instance (through setTime(Date date)). You can then use the DAY_OF_WEEK to get a number representing the days of the week.
Upvotes: 0