Get Date based on day count in Java

后端 未结 7 1101
感情败类
感情败类 2021-01-13 21:46

Simple Question, but Google surprisingly had little on this. I have the number of days from Jan 1st of the year. How can I convert that to a date i

7条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-13 22:15

    You can simply use SimpleDateFormat to convert String to Date. The pattern D can be used to represent the day number of year.

    Provided that you've an

    int numberOfDays = 42; // Arbitrary number.
    

    then this one counts the number of days since 1 Jan 1970 (the Epoch)

    Date date = new SimpleDateFormat("D").parse(String.valueOf(numberOfDays));
    

    alternatively, this one counts the number of days since 1 Jan of current year.

    Date date = new SimpleDateFormat("D yyyy").parse(numberOfDays + " " + Calendar.getInstance().get(Calendar.YEAR));
    

提交回复
热议问题