Get value of day month from Date object in Android?
JavaAndroidDateSimpledateformatJava Problem Overview
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.
Java Solutions
Solution 1 - Java
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
Solution 2 - Java
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);
Solution 3 - Java
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";
Solution 4 - Java
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?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
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.
Solution 5 - Java
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));
Solution 6 - Java
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
Solution 7 - Java
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
Solution 8 - Java
In Kotlin you can also get Current Day Name using this. (Requires API level 26)
(Calendar.getInstance() as GregorianCalendar).toZonedDateTime().dayOfWeek
Solution 9 - Java
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
Solution 10 - Java
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");