Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current date, month, year in scala

Tags:

scala

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

like image 973
toofrellik Avatar asked Sep 29 '16 13:09

toofrellik


3 Answers

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.

like image 125
toofrellik Avatar answered Oct 19 '22 08:10

toofrellik


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
like image 36
sarveshseri Avatar answered Oct 19 '22 10:10

sarveshseri


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.

like image 28
alwe Avatar answered Oct 19 '22 08:10

alwe