I receive a timestamp from a SOAP service in milliseconds. So I do this:
Date date = new Date( mar.getEventDate() );
How can I extract the day of the month from date, since methods such as Date::getDay()
are deprecated?
I am using a small hack, but I do not think this is the proper way to obtain day-of-month.
SimpleDateFormat sdf = new SimpleDateFormat( "dd" );
int day = Integer.parseInt( sdf.format( date ) );
The DAY function takes just one argument, the date from which you want to extract the day. In the example, the formula is: = DAY ( B5 ) B5 contains a date value for January 5, 2016.
If you want to get a day from a date in a table, use the SQL Server DAY() function. This function takes only one argument – the date. This can be a date or date and time data type. (In our example, the column VisitDate is of the date data type.)
Select the date, then go to Format Cells > Custom, and enter one of these formats: dddd, ddd, dd, d. In this example, the cell value is still the date March 12, 2020, but it is displayed as the number 12.
Use Calendar
for this:
Calendar cal = Calendar.getInstance();
cal.setTime(mar.getEventDate());
int day = cal.get(Calendar.DAY_OF_MONTH);
Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.
See the correct Answer by Ortomala Lokni, using the modern java.time classes. I am leaving this outmoded Answer intact as history.
The Answer by Lokni is correct.
Here is the same idea but using Joda-Time 2.8.
long millisSinceEpoch = mar.getEventDate() ;
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ; // Or DateTimeZone.UTC
LocalDate localDate = new LocalDate( millisSinceEpoch , zone ) ;
int dayOfMonth = localDate.getDayOfMonth() ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With