How to write functions for CurrentYear and PreviousYear in scala? - scala

I have this scenario where I am fetching for CurrentDate. Adding to that I also want to fetch data from CurrentYear and PreviousYear
def getCurrentDate: String = {
val cal = Calendar.getInstance()
cal.add(Calendar.DATE, amount = 0)
new SimpleDateFormat(pattern = "yyyyMMdd").format(cal.getTime())
}
def getCurrentYear: String = {
val cal = Calendar.getInstance()
cal.add(Calendar.DATE, amount = 0)
new SimpleDateFormat(pattern = "yyyyMMdd").format(cal.getTime())
}
I am actually figuring out on how to write this simple function

First of all, you need to know that the current year depends on your timezone.
So you first need to choose the timezone for which you want to know the year... specially in edge scenarios like new years eve.
That being said, you can do this:
import java.time._
val yourTZ: ZoneId = ...
def currentDate = Instant.now.atZone(yourTZ).toString.take(10) // because the toString uses ISO formatting
def currentYear = currentDate.take(4)
def previousYear = (currentYear.toInt-1).toString

Related

How to add Month or day to a current/chosen date Kotlin

I created a datepicker and users are able to pick a date from it, in another textview i want to show the date of one exact month later. (E.g. User chooses 25th of February, the view will show 25th of March)
val simpleDateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
val getDate :Calendar = Calendar.getInstance()
val datepicker = DatePickerDialog(this,android.R.style.Theme_Holo_Light_Dialog_MinWidth,DatePickerDialog.OnDateSetListener
{ datePicker, i, i2, i3 ->
val selectDate :Calendar = Calendar.getInstance()
selectDate.set(Calendar.YEAR,i)
selectDate.set(Calendar.MONTH,i2)
selectDate.set(Calendar.DAY_OF_MONTH,i3)
val date :String = simpleDateFormat.format(selectDate.time)
sulusText.setText(date)
},getDate.get(Calendar.YEAR),getDate.get(Calendar.MONTH),getDate.get(Calendar.DAY_OF_MONTH))
datepicker.show()
}
}
So here user can choose the date with sulustext and in another view i'd like show the date of one month later.
LocalDate would be a lot easier.
You can create a LocalDate based on the date picker, and then use a built in method to add one month
import java.time.LocalDate
val today = LocalDate.now()
data class DatePicker(val day: Int, val month: Int)
val datePicker = DatePicker(15, 2)
val baseMonth = LocalDate.of(today.year, datePicker.month, datePicker.day)
// add one month
val nextMonth = LocalDate.from(baseMonth).plusMonths(1)
Note: The data class in the example is for demonstration purposes only. You could replace it with your actual date picker implementation.
I've written function that gets a current day of month (integer) and return new day of month incremented by needed value. In my case it's a week. If you have a question please ask me.
#SuppressLint("SimpleDateFormat")
private fun getNewDayOfMonth(day: Int): String {
val calendar = Calendar.getInstance()
var dayOfMonth = day.toString()
val simpleDateFormat = SimpleDateFormat("dd")
calendar.time = simpleDateFormat.parse(dayOfMonth) as Date
calendar.add(Calendar.DATE, 7)
dayOfMonth = simpleDateFormat.format(calendar.time)
return dayOfMonth
}

Date/Time formatting Scala

I'm trying to assert date and time displayed on the page
Problem is it's returning value of "2017-03-11T09:00" instead of "2017-03-11 09:00:00" and I'm confused why as the pattern = yyyy-MM-dd HH:mm:ss
Any ideas?
def getDate :String = {
val timeStamp = find(xpath("//*[#id=\"content\"]/article/div/div/table/tbody/tr[5]/td/div/p[4]")).get.underlying.getText
val stripDate: Array[String] = timeStamp.split("Timestamp:\n")
stripDate(1)
}
def datePattern(date: String): LocalDateTime = {
val pattern: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val result = LocalDateTime.parse(date, pattern)
result
}
def checkDatePattern() = datePattern(getDate).toString shouldBe getDate
The DateTimeFormatter only gets used for the parse operation. It doesn't influence the result of toString. If you want to convert your LocalDateTime to a String in a certain format you have to call
date.format(pattern)
I've managed to get the result I wanted by just deleting some parts of the code. As long as the date is in displayed in the correct format, the test passes if it's displayed in an incorrect format it fails, which is good enough for me. Thanks for your input. CASE CLOSED
def getDate :String = {
val timeStamp = find(xpath("//*[#id=\"content\"]/article/div/div/table/tbody/tr[5]/td/div/p[4]")).get.underlying.getText
val stripDate: Array[String] = timeStamp.split("Timestamp:\n")
stripDate(1)
}
def datePattern(date: String): LocalDateTime = {
val pattern: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
LocalDateTime.parse(date, pattern)
}
def checkDatePattern() = datePattern(getDate)

Create a list of String elements entitles according to dates

I want to create a list of String elements, each one having a date in its title:
data_2017_May_4
data_2017_May_3
data_2017_May_2
The important thing is how these dates are created. They should be created starting from current date till minus 2 days. If the current date is May 1 2017, then the result would be:
data_2017_May_1
data_2017_April_30
data_2017_April_29
The same logic is applied to the switch between years (December/January).
This is my code, but it does not consider the changes of months and years. Also it jumps in dates:
val formatter = new SimpleDateFormat("yyyy-MMM-dd")
val currDay = Calendar.getInstance
var list: List[String] = Nil
var day = null
var date: String = ""
for (i <- 0 to 2) {
currDay.add(Calendar.DATE, -i)
date = "data_"+formatter.format(currDay.getTime)
list ::= date
}
println(list.mkString(","))
How to reach the objective?
Can you use java.time.LocalDate? If so you can easily accomplish this:
import java.time.LocalDate
import java.time.format.DateTimeFormatter
val desiredFormat = DateTimeFormatter.ofPattern("yyyy-MMM-dd")
val now = LocalDate.now()
val dates = Set(now, now.minusDays(1), now.minusDays(2))
dates.map(_.format(desiredFormat))
.foreach(date => println(s"data_$date"))

Convert time (without date) to UTC time in Scala

I have a string of time I need to parse that's currently in a 12 hour clock format. Some examples are the following:
11:30 PM
07:00 AM
These times are currently in eastern time zone. What's the best way to convert those strings to a string that contains the UTC equivalent?
How about:
import java.text.SimpleDateFormat
val fmtFromLocal = new SimpleDateFormat("hh:mm a z") // z parses time zone
val fmtToGmt = new SimpleDateFormat("hh:mm a")
def toGmt(t: String): String = fmtToGmt.format(fmtFromLocal.parse(s + " EST"))
Unfortunately, this fails when the local timezone is not GMT, as .parse() returns a local time.
Corrected:
import java.text.SimpleDateFormat
import java.util.{Date, TimeZone}
val localTz = TimeZone.getDefault()
val currentOffset = localTz.getOffset(System.currentTimeMillis)
val fmtFromLocal = new SimpleDateFormat("hh:mm a z") // z parses time zone
val fmtToGmt = new SimpleDateFormat("hh:mm a")
def toGmt(t: String): String = {
val time = fmtFromLocal.parse(t).getTime()
val timeUtc = time + currentOffset
fmtToGmt.format(new Date(timeUtc))
}
(Not tested)
Use Joda-Time.
val tz = DateTimeZone.forTimeZone(TimeZone.getTimeZone("EST"))
// You can also use DateTimeZone.forID(), but it requires an id in form
// like 'Europe/Paris', but I don't remember which such ID corresponds to Eastern time
val fmt = DateTimeFormat.forPattern("hh:mm a")
val fmtIn = fmt.withZone(tz)
val fmtOut = fmt.withZone(DateTimeZone.UTC)
val strIn = "11:30 PM"
val strOut = fmtOut.print(fmtIn.parseDateTime(strIn))
Easy and pretty straightforward. I'm getting 04:40 AM for 11:30 PM, which seems to be correct, and I'm in UTC+4 zone, so it this method works independently on local time zone.

Convert String "22/08/2013" to date format 2013/08/22

This is my code in scala
var s:String ="22/08/2013"
var simpleDateFormat:SimpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
var date:Date = simpleDateFormat.parse(s);
println(date)
the date is not change. the format of date same as 22/08/2013 there is no change to 2013/08/22
How to change the format dd/mm/yyyy to yyyy/mm/dd in scala
You need to define a SimpleDateFormat which first parses your string and get Date from it. And then convert it to whatever format.
var s:String ="22/08/2013"
var simpleDateFormat:SimpleDateFormat = new SimpleDateFormat("dd/mm/yyyy");
var date:Date = simpleDateFormat.parse(s);
val ans = new SimpleDateFormat("yyyy/mm/dd").format(date)
println(ans)
I tried this it works for me.
val s: String = "22/08/2013"
val simpleDateFormat: SimpleDateFormat = new SimpleDateFormat("dd/mm/yyyy")
val date = simpleDateFormat.parse(s)
val df = new SimpleDateFormat("yyyy/mm/dd")
println(df.format(date))
There's a subtle error in John Vishal's answer:
mm defines 08 as minutes, not as month. Use MM instead.
Corrected code:
val s = "2013_08_14"
val simpleDateFormat: SimpleDateFormat = new SimpleDateFormat("yyyy_MM_dd")
val date = simpleDateFormat.parse(s)
val df = new SimpleDateFormat("dd-MMM-yyyy")
println(df.format(date))