65

By using this code :

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(dtStart);
return date;

I have converted the String Date by Date Object and get the value:

Sun Feb 17 07:00:00 GMT 2013

Now I want to extract day (Sunday/Monday) and month from here.

halfer
  • 19,824
  • 17
  • 99
  • 186
NRahman
  • 2,717
  • 5
  • 24
  • 29
  • possible duplicate of [Android: how to get the current day of the week (Monday, etc...) in the user's language?](http://stackoverflow.com/questions/7651221/android-how-to-get-the-current-day-of-the-week-monday-etc-in-the-users-l) – Basil Bourque Aug 15 '15 at 18:57
  • 1
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Dec 16 '18 at 06:53

10 Answers10

221
import android.text.format.DateFormat;

String dayOfTheWeek = (String) DateFormat.format("EEEE", date); // Thursday
String day          = (String) DateFormat.format("dd",   date); // 20
String monthString  = (String) DateFormat.format("MMM",  date); // Jun
String monthNumber  = (String) DateFormat.format("MM",   date); // 06
String year         = (String) DateFormat.format("yyyy", date); // 2013
Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
Pankaj Kumar
  • 81,967
  • 29
  • 167
  • 186
28

You can try:

String input_date="01/08/2012";
SimpleDateFormat format1=new SimpleDateFormat("dd/MM/yyyy");
Date dt1=format1.parse(input_date);
DateFormat format2=new SimpleDateFormat("EEEE"); 
String finalDay=format2.format(dt1);

Also try this:

Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
amalBit
  • 12,041
  • 6
  • 77
  • 94
4

to custom days of week you can use this function

public static String getDayFromDateString(String stringDate,String dateTimeFormat)
{
    String[] daysArray = new String[] {"saturday","sunday","monday","tuesday","wednesday","thursday","friday"};
    String day = "";

    int dayOfWeek =0;
    //dateTimeFormat = yyyy-MM-dd HH:mm:ss
    SimpleDateFormat formatter = new SimpleDateFormat(dateTimeFormat);
    Date date;
    try {
        date = formatter.parse(stringDate);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        dayOfWeek = c.get(Calendar.DAY_OF_WEEK)-1;
        if (dayOfWeek < 0) {
            dayOfWeek += 7;
        }
        day = daysArray[dayOfWeek];
    } catch (Exception e) {
        e.printStackTrace();
    }

    return day;
}

dateTimeFormat for example dateTimeFormat = "yyyy-MM-dd HH:mm:ss";

3

tl;dr

If your date and time were meant for UTC:

LocalDateTime               // Represent a date and time-of-day lacking the context of a time zone or offset-from-UTC. Does *NOT* represent a moment.
.parse(                     // Convert from text to a date-time object.
    "2013-02-17 07:00:00" 
    .replace( " " , "T" )   // Comply with standard ISO 8601 format.
)                           // Returns a `LocalDateTime` object.
.atOffset(                  // Determining a moment by assign an offset-from-UTC. Do this only if you are certain the date and time-of-day were intended for this offset.
    ZoneOffset.UTC          // An offset of zero means UTC itself.
)                           // Returns a `OffsetDateTime` object. Represents a moment.
.getDayOfWeek()             // Extract the day-of-week enum object.
.getDisplayName(            // Localize, producing text. 
    TextStyle.FULL ,        // Specify how long or abbreviated.
    Locale.US               // Specify language and cultural norms to use in localization.
)                           // Returns a `String` object.

Sunday

And…

…
.getMonth()
.getDisplayName( TextStyle.FULL , Locale.US )

February

java.time

The modern solution uses the java.time classes that years ago supplanted the terrible old date-time classes such as Date & SimpleDateFormat.

Time zone

Your code ignores the crucial issue of time zone. When you omit an specific zone or offset-from-UTC, the JVM’s current default time zone is implicitly applied. So your results may vary.

Instead, always specify a time zone or offset explicitly in your code.

LocalDateTime

Your input format of YYYY-MM-DD HH:MM:SS lacks an indicator of time zone or offset-from-UTC.

So we must parse as a LocalDateTime.

Your input format is close to the standard ISO 8601 format used by default in the LocalDateTime class. Just replace the SPACE in the middle with a T.

String input = "2013-02-17 07:00:00".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;

ldt.toString(): 2013-02-17T07:00

The LocalDateTime you now have in hand does not represent a moment, is not a point on the timeline. Purposely lacking a time zone or offset means it cannot, by definition, represent a moment. A LocalDateTime represents potential moments along a range of about 26-27 hours, the range of time zones around the globe.

ZonedDateTime

If you know for certain a time zone intended for that date and time, apply a ZoneId to get a ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

With a ZonedDateTime, you now have a moment.

Get the day-of-week using the DayOfWeek enum.

DayOfWeek dow = zdt.getDayOfWeek() ;

The DayOfWeek::getDisplayName method translates the name of the day into any human language specified by a Locale such as Locale.US or Locale.CANADA_FRENCH.

String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ); 

dimanche

Or, in US English.

String output = dow.getDisplayName( TextStyle.FULL , Locale.US ); 

Sunday

Similar for month, use Month enum.

Month m = zdt.getMonth() ;

String output = m.getDisplayName( TextStyle.FULL , Locale.US ); 

February

OffsetDateTime

If you know for certain that date and time-of-day in the LocalDateTime was meant to represent a moment in UTC, use OffsetDateTime class.

OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;  // Assign UTC (an offset of zero hours-minutes-seconds). 

MonthDay

You may also be interested in the MonthDay class if you wish to work with a day and a month without a year.

MonthDay md = MonthDay.from( zdt ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
3

Also in Kotlin :

    val string = "2020-01-13T00:00:00"
    val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US)
    val date = format.parse(string)

    val day = DateFormat.format("dd", date) as String
    val monthNumber = DateFormat.format("MM", date) as String
    val year = DateFormat.format("yyyy", date) as String
iluxa.b
  • 375
  • 1
  • 6
  • 16
  • 1
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Jan 13 '20 at 17:07
2

Consider using the java.util.Calendar class.

String dateString = "20/12/2018";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

Date readDate = df.parse(dateString);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(readDate.getTime());

Log.d(TAG, "Year: "+cal.get(Calendar.YEAR));
Log.d(TAG, "Month: "+cal.get(Calendar.MONTH));
Log.d(TAG, "Day: "+cal.get(Calendar.DAY_OF_MONTH));
Slim89
  • 29
  • 2
2

In Kotlin you can also get Current Day Name using this. (Requires API level 26)

(Calendar.getInstance() as GregorianCalendar).toZonedDateTime().dayOfWeek
Sajjad Javed
  • 139
  • 2
  • 14
2
 Calendar calendar = Calendar.getInstance();
   DateFormat date= new SimpleDateFormat("EEEE", Locale.getDefault());
    String dayName= date.format(calendar.getTime()); //Monday
    date = SimpleDateFormat("EE", Locale.getDefault());
    dayName = date2.format(calendar.time); //Sun
    date= new SimpleDateFormat("dd", Locale.getDefault());
    String dayNumber = date.format(calendar.getTime()); //20
    date= new SimpleDateFormat("MMM", Locale.getDefault());
    String monthName= date.format(calendar.getTime()); //Apr
    date= new SimpleDateFormat("MM", Locale.getDefault());
    String monthNumber= date.format(calendar.getTime()); //04
    date= new SimpleDateFormat("yyyy", Locale.getDefault());
    String year= date.format(calendar.getTime()); //2020

that's it. enjoy

Noaman Akram
  • 3,680
  • 4
  • 20
  • 37
1
public static String getDayFromStringDate(String stringDate, String dateFormat, boolean abbreviated) throws ParseException {

    String pattern;

    if (abbreviated) {

        pattern = "E"; // For short day eg: Mon,Tue
    } else {

        pattern = "EEEE"; // For compete day eg: Monday, Tuesday
    }

    return new SimpleDateFormat(pattern)
            .format(new SimpleDateFormat(dateFormat).parse(stringDate));
}

Eg: if stringDate :- 16/12/2018 then dateFormat : - dd/MM/yyyy

pvrforpranavvr
  • 2,708
  • 2
  • 24
  • 34
  • 2
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Dec 16 '18 at 06:53
-1
selecteddate = "Tue Nov 26 15:49:25 GMT+05:30 2019";

SimpleDateFormat dateUI = new SimpleDateFormat("EEEE, dd-MMMM-yyyy");

String date = dateUI.foramt(selecteddate);

Log.e(context,"date");