2

I want to convert date into desired format. I know first i need to convert into date then need to format that date. My question is any easiest way to do in simple form. Is there any impact on performance? Because i have all these dates in list.

for example

fun main(vararg args: String) {
    val dateString = "2021-05-12T12:12:12.121Z"
    val convertedDate = convertDate(dateString)
    print(
            convertedDate?.let {
                formatDate(it)
            }
    )
}

fun formatDate(date: Date): String {
    return SimpleDateFormat("MMM dd, YYYY").format(date)
}

fun convertDate(dateString: String): Date? {
    return SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(dateString)
}

Output

May 12, 2021
Kotlin Learner
  • 3,995
  • 6
  • 47
  • 127
  • If you're not formatting multiple things in parallel, you can declare the 2 `SimpleDateFormat`s once and reuse them for every date. Apart from that, this looks good to me. – Joffrey Jun 11 '21 at 16:26
  • thanks for reply @Joffrey. What do you mean `you can declare the 2 SimpleDateFormats once and reuse them for every date` can you explain me in detail please? – Kotlin Learner Jun 11 '21 at 16:28
  • is my above example is good to use @Joffrey – Kotlin Learner Jun 11 '21 at 16:30
  • In this example, you're only converting one string, but you mentioned you wanted to convert many. What I meant is that your current functions create new formats each time they are called (because they call the `SimpleDateFormat(...)` constructor). You can extract these format instances into variables and reuse them for each string in your list. This also applies if you use the new APIs mentioned by @Arvind. – Joffrey Jun 11 '21 at 16:40

1 Answers1

5

The standard Date-Time classes do not have any attribute to hold the formatting information. Even if some library or custom class promises to do so, it is breaking the Single Responsibility Principle. A Date-Time object is supposed to store the information about Date, Time, Timezone etc., not about the formatting. The only way to represent a Date-Time object in the desired format is by formatting it into a String using a Date-Time parsing/formatting type:

  • For the modern Date-Time API: java.time.format.DateTimeFormatter
  • For the legacy Date-Time API: java.text.SimpleDateFormat

Note that the java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*, released in March 2014 as part of Java SE 8 standard library.

Apart from that, there are many things wrong with your code:

  1. Using Y ( Week year) instead of y (Year). Check the documentation to learn more about it.
  2. Not using Locale with SimpleDateFormat. Check Never use SimpleDateFormat or DateTimeFormatter without a Locale to learn more about it.
  3. Enclosing Z within single quotes means it is just a character literal with no meaning other than representing the letter Z. The pattern, yyyy-MM-dd'T'HH:mm:ss.SSS'Z' should be yyyy-MM-dd'T'HH:mm:ss.SSSXXX.

Solution using java.time, the modern Date-Time API:

import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        var dateString = "2021-05-12T12:12:12.121Z";
        var odt = OffsetDateTime.parse(dateString);
        var dtf = DateTimeFormatter.ofPattern("MMM dd, uuuu", Locale.ENGLISH);
        System.out.println(dtf.format(odt));
    }
}

Output:

May 12, 2021

ONLINE DEMO

Here, you can use y instead of u but I prefer u to y.

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Thanks for reply @Arvind ji. what is `uuuu` in **ofPattern** – Kotlin Learner Jun 11 '21 at 16:41
  • @vivekmodi - You are most welcome and I wish you success! Here, you can use `y` instead of `u` but [I prefer `u` to `y`](https://stackoverflow.com/a/65928023/10819573). Now, I have put this information in the answer as well. – Arvind Kumar Avinash Jun 11 '21 at 16:43
  • if i want to date object instead of string. How can i do it ? – Kotlin Learner Jun 11 '21 at 16:48
  • It is not possible with standard Date-Time classes as they do not have any attribute to hold the formatting information. Even if some library or custom class promises to do so, it is breaking the [Single Responsibility Principle](https://en.wikipedia.org/wiki/Single-responsibility_principle). A Date-Time object is supposed to store the information about date, time, timezone etc., but not about the formatting. – Arvind Kumar Avinash Jun 11 '21 at 16:50