How to put the range of dates in a specific format? - scala

I am using Joda time to generate a range of dates as follows:
val now = DateTime.now
(0 until 5).map(now.minusDays(_)).foreach(println)
How can I parse the generated dates to yyyy-MM-dd format. I was getting the error "java.lang.IllegalArgumentException: Invalid format" when using DateTimeFormat:
val dtf = DateTimeFormat.forPattern("yyyy-MM-dd")
(0 until 5).map(now.minusDays(_)).foreach(d=>dtf.parseDateTime(d.toString))

Change to:
val now = DateTime.now
(0 until 5).map(now.minusDays(_)).map(d=> d.toString("yyyy-MM-dd"))

Related

Java.util.Calendar.add() function in scala

val now = Calendar.getInstance();
val toDt= now.get(Calendar.MONTH)
val fromDt= now.add(Calendar.MONTH,-6)
I am trying fetch minus 6 month date value by using above code. Looks like now.add is generating Unit value
val fromDt = now.clone().asInstanceOf[Calendar]
fromDt.add(Calendar.MONTH, -6) // after call `add` method, the `fromDt` internal state has changed, so you can use `fromDt` directly. like below `print`
println(fromDt.get(Calendar.MONTH))
> 7
You can clone calendar and add Month.

Format yyyy-MM-dd HH:mm:ss from String to date Format

What I am encountering is quite peculiar.
My Code:
val aa = "2017-01-17 01:33:00"
val bb = "04:33"
val hour = bb.substring(0, bb.indexOf(":"))
val mins = bb.substring(bb.indexOf(":") + 1, bb.length())
val negatedmins = "-" + mins
val ecoffsethour = hour.toLong
val ecoffsetmins = negatedmins.toLong
println(aa)
val datetimeformatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val txn_post_date_hkt_date_parsed = LocalDateTime.parse(aa, datetimeformatter)
println(txn_post_date_hkt_date_parsed)
val minushours = txn_post_date_hkt_date_parsed.minusHours(ecoffsethour)
println(minushours)
val minusmins = minushours.minusMinutes(ecoffsetmins)
println(minusmins)
val offsetPostdateDiff = minusmins.toString().replace("T", " ")
println(offsetPostdateDiff)
Output:
2017-01-17 01:33:00
2017-01-17T01:33
2017-01-16T21:33
2017-01-16T22:06
2017-01-16 22:06
In the same code I am changing only the "aa" value to ==> 2017-01-17 01:33:44
Now the output is :
2017-01-17 01:33:44
2017-01-17T01:33:44
2017-01-16T21:33:44
2017-01-16T22:06:44
2017-01-16 22:06:44
Why is the first method not taking seconds field into consideration?
My Requirement is : However the output should come in "yyyy-MM-dd
HH:mm:ss" format.
I'm quite new to Scala. Please enlighten me.
Default format is ISO 8601
The java.time classes use the standard ISO 8601 formats by default when parsing/generating strings to represent date-time value.
The standard format for a local date-time is what you are seeing with the T in the middle: YYYY-MM-DDTHH:MM:SS.SSSSSSSSS.
LocalDateTime ldt = LocalDateTime.now( ZoneId.of( "America/Montreal" ) ) ;
String output = ldt.toString() ;
2017-01-23T12:34:56.789
Your call println( txn_post_date_hkt_date_parsed ) is implicitly calling the built-in toString method on the LocalDateTime object, and thereby asking for the standard ISO 8601 format with the T.
println( txn_post_date_hkt_date_parsed.toString() )
Offsets
On an unrelated note, you are working too hard. The java.time classes handle offsets. I do not understand why you want an offset of such an odd number (four hours and thirty-three minutes), but so be it.
Here is your code revised, but in Java syntax.
String input = "2017-01-17 01:33:00" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
OffsetDateTime utc = ldt.atOffset( ZoneOffset.UTC ) ;
ZoneOffset offset = ZoneOffset.of( "-04:33" ) ; // Behind UTC by four hours and thirty-three minutes.
OffsetDateTime odt = utc.withOffsetSameInstant( offset ) ;
You can see this code run live at IdeOne.com. Notice how the wall-clock time of your offset-from-UTC is on the previous date. Same moment in history, same point on the timeline, but viewed through two different wall-clock times (UTC, and four hours and thirty three minutes behind).
The Z on the end is standard ISO 8601 notation, short for Zulu and meaning UTC.
input: 2017-01-17 01:33:00
ldt.toString(): 2017-01-17T01:33
utc.toString(): 2017-01-17T01:33Z
odt.toString(): 2017-01-16T21:00-04:33
It's usually better to explicitly the format in which you want the output.
So, instead of
println datetime
You can do something like this:
println datetimeformat.print(datetime)
Good luck!
Edit: Change made to make the 2 expressions exactly equivalent

Get year, month and day from parsed date

I have the following code to validate a date given a date format:
val df = new SimpleDateFormat("MM/dd/yyyy");
df.setLenient(false);
try {
val date = df.parse("11/13/2014");
}
catch {
case pe: ParseException => println("date error")
}
Now, what I need is to obtain the year, month and day in three variables. What is the best way to achieve this? Note that I need a solution based on performance as I need to validate/convert thousands of dates.
java.time
Use Java 8 and the new date/time API. Better, cleaner, future-proof.
val dateFormat = "MM/dd/yyyy"
val dtf = java.time.format.DateTimeFormatter.ofPattern(dateFormat)
val dateString = "11/13/2014"
val d = java.time.LocalDate.parse(dateString, dtf)
val year = d.getYear
2014
val monthNumber = d.getMonthValue
11
You can access a Month enum object.
val month = d.getMonth
Month.NOVEMBER
val dayOfMonth = d.getDayOfMonth
13
Once you have the input parsed into a java.time.LocalDate, you can get the year with getYear, etc.
To validate, catch the DateTimeParseException generated for invalid inputs.
If you want to skip the proper date validation (e.g. for performance) and just extract the Y, M, D - you can split the string and get integers as shown below
val ymd = dateString.split("/").map(_.toInt)
ymd: Array[Int] = Array(11, 13, 2014)

Parsing Date in Java using SimpleDateFormat

Developing an Application where i have to parse the following date:
2015-02-02T11:21:51.895Z
using SimpleDateFormat class. But I am getting a Date Parsing Exception.
Here is my code snippet:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss'Z'");`
Date qdate = new GregorianCalendar(0,0,0).getTime();
try {
qdate = sdf.parse(dt);
} catch (ParseException e) {
}
Regarding your input "2015-02-02T11:21:51.895Z" you should see that your assumed pattern does not match the input because the pattern does not expect the millisecond part but the literal "Z".
Beyond this, the pattern you used is wrong because of following reasons:
m = minute
M = month
h = hour of half day (1-12)
H = hour of full day (0-23)
X = timezone designator (because Z is not a literal but stands for UTC+00:00)
So you need (please also refer to javadoc):
yyyy-MM-dd'T'HH:mm:ss.SSSX
There is an error in your format (add .SSS for the miliseconds):
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss.SSS'Z'");
Date date = sdf.parse("2015-02-02T11:21:51.895Z");

Groovy date format for UTC with milliseconds

I'm having trouble finding a good way of formatting a UTC-time stamp with this format: yyyyMMdd-HH:mm:ss.<three additional digits>
I wasn't able to find any character that represents milliseconds/hundredths, I'm not even sure this is possible, to parse that format that is.
Ideally I'd like to use the parseToStringDate that's part of the Date library.
My plan b is to convert yyyyMMdd-HH:mm:ss to milliseconds and then add the three last digits to that number.
Use yyyyMMdd-HH:mm:ss.SSS
This will get you milliseconds as well.
Test Code:
def now = new Date()
println now.format("yyyyMMdd-HH:mm:ss.SSS", TimeZone.getTimeZone('UTC'))
I would convert it like that:
def now = new Date()
println now.format("YYYYMMdd-HH:mm:ss")
You can try this:
TimeZone.getTimeZone('UTC')
Date date = new Date()
String newdate = date.format("YYYY-MM-dd HH:mm:ss.Ms")
log.info newdate