vignesh asokan
vignesh asokan

Reputation: 145

Get date out of year and day of year from a value - Scala

I have a 6 digit value from which i have to get the date in scala. For eg if the value is - 119003 then the output should be

1=20 century
19=2019 year
003= january 3

The output should be 2019/01/03

I have tried ti split the value first and then get the date. But i am not sure how to proceed as i am new to scala

Upvotes: 1

Views: 650

Answers (2)

Anonymous
Anonymous

Reputation: 86343

The Date class of Java 1.0 used 1900-based years, so 119 would mean 2019, for example. This use was deprecated already in Java 1.1 more than 20 years ago, so it’s surprising to see it survive into Scala.

When you say 6 digit value, I take it to be a number (not a string).

The answer by jwvh is correct. My variant would be like (sorry about the Java code, please translate yourself):

    int value = 119003;
    int year1900based = value / 1000;
    int dayOfYear = value % 1000;
    LocalDate date = LocalDate.ofYearDay(year1900based + 1900, dayOfYear);
    System.out.println(date);

2019-01-03

If you’ve got a string, I would slice it into two parts only, 119 and 003 (not three parts as in your comment). Parse each into an int and proceed as above.

If you need 2019/01/03 format in your output, use a DateTimeFormatter for that. Inside your program, do keep the LocalDate, not a String.

Upvotes: 1

jwvh
jwvh

Reputation: 51271

I think you'll have to do the century calculations manually. After that you can let the java.time library do all the rest.

import java.time.LocalDate
import java.time.format.DateTimeFormatter

val in = "119003"
val cent = in.head.asDigit + 19
val res = LocalDate.parse(cent+in.tail, DateTimeFormatter.ofPattern("yyyyDDD"))
                   .format(DateTimeFormatter.ofPattern("yyyy/MM/dd"))
//res: String = 2019/01/03

Upvotes: 4

Related Questions