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