Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract day from Date

Tags:

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 ) );
like image 866
Daniel Avatar asked Apr 12 '10 03:04

Daniel


People also ask

How do I extract a day from a date in Excel?

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.

How do I extract just the day from a date in SQL?

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.)

How do I extract a day from a date in sheets?

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.


2 Answers

Use Calendar for this:

Calendar cal = Calendar.getInstance();
cal.setTime(mar.getEventDate());
int day = cal.get(Calendar.DAY_OF_MONTH);
like image 188
cletus Avatar answered Sep 18 '22 17:09

cletus


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() ;
like image 44
Basil Bourque Avatar answered Sep 17 '22 17:09

Basil Bourque