Difference between UTC Time values scala - scala

I would like to perform difference between UTC current time and a UTC value in scala.

How about the following?
import java.time._
val time1 = Instant.parse("2017-01-01T12:00:00Z")
val time2 = Instant.now()
val diff = Duration.between(time1, time2)
println("Difference is " + diff)
println("or in seconds: " + diff.getSeconds())
Try it here
Further reading:
https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html
https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html
https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html

Related

Get previous 12months with month end date from given month using Scala

I had an use-case to fetch last 12months with end-date of that month from given date.
For Example if I give input as ('2021-04-23'), the output should be:
output1 = ('2021-04-30', '2021-03-31', '2021-02-28', '2021-01-31', '2020-12-31', '2020-11-30', '2020-10-31', '2020-09-30', '2020-08-31', '2020-07-31', '2020-06-30', '2020-05-31', '2020-04-30')
output2=('2021-04-01','2021-03-01','2021-02-01','2021-01-01','2020-12-01','2020-11-01','2020-10-01','2020-09-01', '2020-08-01','2020-07-01','2020-06-01','2020-05-01','2020-04-01')
I had the code snippet
import java.time.format.DateTimeFormatter
val monthDate = DateTimeFormatter.ofPattern("yyyy-MM")
val start = YearMonth.parse("2021-04", monthDate
val lastTwelveMonths=(0 to 12).map(x => start.minusMonths(x).format(monthDate)).toList
which returns last 12months from current month, Can any one please provide solution which includes end date too for previous 12 months. Thanks
You can use java.time.LocalDate's withDayOfMonth() for what you need:
import java.time.LocalDate
import java.time.format.DateTimeFormatter
val dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val inputDate = LocalDate.parse("2021-04-23")
(0 to 12).map{ n =>
inputDate.minusMonths(n).withDayOfMonth(1).format(dateFormat)
}
// Vector(2021-04-01, 2021-03-01, 2021-02-01, 2021-01-01, 2020-12-01, 2020-11-01, 2020-10-01, 2020-09-01, 2020-08-01, 2020-07-01, 2020-06-01, 2020-05-01, 2020-04-01)
(0 to 12).map{ n =>
val prevDate = inputDate.minusMonths(n)
prevDate.withDayOfMonth(prevDate.lengthOfMonth).format(dateFormat)
}
// Vector(2021-04-30, 2021-03-31, 2021-02-28, 2021-01-31, 2020-12-31, 2020-11-30, 2020-10-31, 2020-09-30, 2020-08-31, 2020-07-31, 2020-06-30, 2020-05-31, 2020-04-30)

Kotlin: Getting the difference betweeen two dates (now and previous date)

Sorry if similar questions have been asked too many times, but it seems that there's one or more issues with every answer I find.
I have a date in the form of a String: Ex.: "04112005"
This is a date. 4th of November, 2005.
I want to get the difference, in years and days, between the current date and this date.
The code I have so far gets the year and just substracts them:
fun getAlderFraFodselsdato(bDate: String): String {
val bYr: Int = getBirthYearFromBirthDate(bDate)
var cYr: Int = Integer.parseInt(SimpleDateFormat("yyyy").format(Date()))
return (cYr-bYr).toString()
}
However, naturally, this is quite innacurate, since the month and days aren't included.
I've tried several approaches to create Date, LocalDate, SimpleDate etc. objects and using these to calcualate the difference. But for some reason I haven't gotten any of them to work.
I need to create a Date (or similar) object of the current year, month and day. Then I need to create the same object from a string containing say, month and year (""04112005""). Then I need to get the difference between these, in years, months and days.
All hints are appreciated.
I would use java.time.LocalDate for parsing and today along with a java.time.Period that calculates the period between two LocalDates for you.
See this example:
fun main(args: Array<String>) {
// parse the date with a suitable formatter
val from = LocalDate.parse("04112005", DateTimeFormatter.ofPattern("ddMMyyyy"))
// get today's date
val today = LocalDate.now()
// calculate the period between those two
var period = Period.between(from, today)
// and print it in a human-readable way
println("The difference between " + from.format(DateTimeFormatter.ISO_LOCAL_DATE)
+ " and " + today.format(DateTimeFormatter.ISO_LOCAL_DATE) + " is "
+ period.getYears() + " years, " + period.getMonths() + " months and "
+ period.getDays() + " days")
}
The output for a today of 2020-02-21 is
The difference between 2005-11-04 and 2020-02-21 is 14 years, 3 months and 17 days
It Works Below 26 API level
There are too many formates of dates you just enter the format of date and required start date and end date. It will show you result. You just see different date formate hare and here if you need.
tvDifferenceDateResult.text = getDateDifference(
"12 November, 2008",
"31 August, 2021",
"dd MMMM, yyyy")
General method to calculate date difference
fun getDateDifference(fromDate: String, toDate: String, formater: String):String{
val fmt: DateTimeFormatter = DateTimeFormat.forPattern(formater)
val mDate1: DateTime = fmt.parseDateTime(fromDate)
val mDate2: DateTime = fmt.parseDateTime(toDate)
val period = Period(mDate1, mDate2)
// period give us Year, Month, Week and Days
// days are between 0 to 6
// if you want to calculate days not weeks
//you just add 1 and multiply weeks by 7
val mDays:Int = period.days + (period.weeks*7) + 1
return "Year: ${period.years}\nMonth: ${period.months}\nDay: $mDays"
}
For legacy Date functions below api 26 without running desugaring with Gradle plugin 4.0, java.time.* use:
fun getLegacyDateDifference(fromDate: String, toDate: String, formatter: String= "yyyy-MM-dd HH:mm:ss" , locale: Locale = Locale.getDefault()): Map<String, Long> {
val fmt = SimpleDateFormat(formatter, locale)
val bgn = fmt.parse(fromDate)
val end = fmt.parse(toDate)
val milliseconds = end.time - bgn.time
val days = milliseconds / 1000 / 3600 / 24
val hours = milliseconds / 1000 / 3600
val minutes = milliseconds / 1000 / 3600
val seconds = milliseconds / 1000
val weeks = days.div(7)
return mapOf("days" to days, "hours" to hours, "minutes" to minutes, "seconds" to seconds, "weeks" to weeks)
}
The above answers using java.time.* api is much cleaner and accurate though.

boto 3 - loosing date format

I'm trying to read a parquet file using boto3. The original file has dates with the following format:
2016-12-07 23:00:00.000
And they are stored as timestamps.
My code in Sage Maker is:
boto_s3 = boto3.client('s3')
r = boto_s3.select_object_content(
Bucket='bucket_name',
Key='path/file.gz.parquet',
ExpressionType='SQL',
Expression=f"select fecha_instalacion,pais from s3object s ",
InputSerialization = {'Parquet': {}},
OutputSerialization = {'CSV': {}},
)
rl0 = list(r['Payload'])[0]
from io import StringIO
string_csv = rl0['Records']['Payload'].decode('ISO-8859-1')
csv = StringIO(string_csv)
pd.read_csv(csv, names=['fecha_instalacion', 'pais'])
But instead of the date I get:
fecha_instalacion pais
45352962065516692798029824 ESPAƃA
I loooked for dates with only one day in between and the nyuumber of digits that are the same are the first 6. As an example:
45337153205849123712294912--> 2016-12-09 23:00:00.000
45337116312360976293191680--> 2016-12-07 23:00:00.000
I would need to get the correct formated date, and avoid the especial characters.
Thanks.
The problem is the format. That Parquet file is using Int96 numbers to represent timestamp.
Here is a function to convert the int96Timestamp to python DateTime
import datetime
def dateFromInt96Timestamp(int96Timestamp):
julianCalendarDays = int96Timestamp >> 8*8
time = int((int96Timestamp & 0xFFFFFFFFFFFFFFFF) / 1_000)
linuxEpoch = 2_440_588
return datetime.datetime(1970, 1, 1) + datetime.timedelta(days=julianCalendarDays - linuxEpoch, microseconds=time)

Date intervals keeping state

My task is to write function, that takes 2 LocalDateTime instances and generate list of intervals, splitted by 15 minutes
case class Interval(start:LocalDateTime, end:LocalDateTime)
so, for example if startDate = 2 Aug 2017 14:30:15 and endDate is 2 Aug 2017 15:00:00, intervals should be
List(Interval(2 Aug 2017 14:30:15, 2 Aug 2017 14:45:15), Interval(2 Aug 2017 14:45:15, 2 Aug 2017 15:00:00))
Here, is 2 main complications(at least for me)
1) If end date is less then prevDate + 15 min, then we need take min from(prevdate + 15 min, endDate)
2) We need somehow keep the state, because start of each interval is end of previous interval.
I am able to create imperative version, but I want to do it in functional style, please, help!)
x => {
var start = x.startTime
var end = min(findRightBorder(start), x.endTime)
var result = ListBuffer(Interval(start, end))
while (end.isBefore(x.endTime)) {
start = end
end = min(start.plusMinutes(QUARTER_MINUTES), x.endTime)
result += Interval(start, end)
}
result.toList
}
private def findRightBorder(dt: LocalDateTime): LocalDateTime = {
val minute = dt.getMinute
if (minute >= 0 && minute < 15) dt.withMinute(15)
else if (minute >= 15 && minute < 30) dt.withMinute(30)
else if (minute >= 30 && minute < 45) dt.withMinute(45)
else if (minute >= 45 && minute < 60) dt.withMinute(0).plusHours(1)
else dt
}
private def min(dt1: LocalDateTime, dt2: LocalDateTime): LocalDateTime = {
if (dt1.compareTo(dt2) < 0) dt1 else dt2
}
Another solution with streams:
x => {
Stream
.from(0)
.map(i => x.startTime.plusMinutes(i * QUARTER_MINUTES))
.takeWhile(_.isBefore(x.endTime))
.map(s => Interval(s, min(s.plusMinutes(QUARTER_MINUTES), x.endTime)))
.toList
}
Here's one way to go about this.
import java.time.LocalDateTime
case class Interval(start:LocalDateTime, end:LocalDateTime)
val dt1: LocalDateTime = ??? //some start DateTime
val dt2: LocalDateTime = ??? //some end DateTime
// a (potentially) infinite Stream of dates at 15 minute intervals
// starting at dt1 but ending before dt2
val dates = Stream.iterate(dt1)(_.plusMinutes(15L))
.takeWhile(_.isBefore(dt2))
val result = dates.sliding(2) //pair the dates together
.toSeq //a Seq is easier to append to
.map{case Seq(from,to) => Interval(from,to)} //make Intervals
.:+(Interval(dates.last,dt2)) //append the final Interval
.toList //if you need a List result

How to change 12 Hours to 24 Hours using Scala

I want 12 Hours Time format convert into 24 Hours time format, Here I attached my code and I checked this link1,link2 but it return as same time format.
Code
val inTime = "12:15 PM"
val newTimeFormat = new SimpleDateFormat("hh:mm a")
val timeWithDateFormat = newTimeFormat.parse(inTime)
val outputTime = newTimeFormat.format(timeWithDateFormat)
println("Output===========>",outputTime)
Output is:
(Output===========>,12:15 PM)
How can I resolved it.
As you want your output to be in a different format than your input, you will need to use a different formatters for input and output.
Also... 12:15 PM of 12-hour-format is 12:15 of 24-hour-format. So may be you should use a different time for this example (lets use 03:15 PM or 15:15),
val inTime = "03:15 PM"
val inputTimeFormat = new SimpleDateFormat("hh:mm a")
val timeWithDateFormat = inputTimeFormat.parse(inTime)
val outputTimeFormat = new SimpleDateFormat("HH:mm")
val outputTime = outputTimeFormat.format(timeWithDateFormat)
println("Output===========>", outputTime)
Just create new SimpleDateFormat and use it to format your date;
val format = new SimpleDateFormat("HH:mm")
For details you can check documentation;
Customizing Formats