Reputation: 1307
i need current year, month & date to 3 different variables. below code gives date time
val now = Calendar.getInstance().getTime()
Thu Sep 29 18:27:38 IST 2016
but i need in YYYY MM and DD format
Upvotes: 6
Views: 31083
Reputation: 1307
val cal = Calendar.getInstance()
val date =cal.get(Calendar.DATE )
val Year =cal.get(Calendar.YEAR )
val Month1 =cal.get(Calendar.MONTH )
val Month = Month1+1
Month is added with one because month starts with zero index.
Upvotes: 10
Reputation: 13985
When you are talking about year
, month
, day-of-month
, hour-of-day
etc... your timezone becomes very important. So whenever you are talking about all these, you have to mention the timezone.
If you are using java 8, you can use the java.time api
import java.time.{ZonedDateTime, ZonedOffset}
// val yourTimeZoneOffset = ZoneOffset.ofHoursMinutesSeconds(hour, minute, second)
// for example IST or Indian Standard Time has an offset of "+05:30:00" hrs
val istOffset = ZoneOffset.ofHoursMinutesSeconds(5, 30, 0)
// istOffset: java.time.ZoneOffset = +05:30
// time representation in IST
val zonedDateTimeIst = ZonedDateTime.now(istOffset)
// zonedDateTimeIst: java.time.ZonedDateTime = 2016-09-29T20:14:48.048+05:30
val year = zonedDateTimeIst.getYear
// year: Int = 2016
val month = zonedDateTimeIst.getMonth
// month: java.time.Month = SEPTEMBER
val dayOfMonth = zonedDateTimeIst.getDayOfMonth
// dayOfMonth: Int = 29
val df1 = DateTimeFormatter.ofPattern("yyyy - MM - dd")
val df2 = DateTimeFormatter.ofPattern("yyyy/MM/dd")
// df1: java.time.format.DateTimeFormatter = Value(YearOfEra,4,19,EXCEEDS_PAD)' ''-'' 'Value(MonthOfYear,2)' ''-'' 'Value(DayOfMonth,2)
// df2: java.time.format.DateTimeFormatter = Value(YearOfEra,4,19,EXCEEDS_PAD)'/'Value(MonthOfYear,2)'/'Value(DayOfMonth,2)
val dateString1 = zonedDateTimeIst.format(df1)
// dateString1: String = 2016 - 09 - 29
val dateString2 = zonedDateTimeIst.format(df2)
// dateString2: String = 2016/09/29
Upvotes: 3
Reputation: 2227
You need to use different SimpleDateFormat objects for that purpose as described here
In your case, you'll need :
import java.text.SimpleDateFormat
val minuteFormat = new SimpleDateFormat("MM")
val yearFormat = new SimpleDateFormat("YYYY")
val dayFormat = new SimpleDateFormat("dd")
And then, to get for example, the year for a given date, simply use :
val currentYear = hourFormat.format(yourDate)
Upvotes: 1
Reputation: 1497
You could use joda-time:
import org.joda.time.DateTime
val date: String = DateTimeFormat.forPattern("yyyy-MM-dd").print(DateTime.now())
val month: Int = DateTime.now().getMonthOfYear
val year: Int = DateTime.now().getYear
In case you use java8 you could also use the native DateTime API, which is designed after the joda-time api.
Upvotes: 1