22

I'm getting date data from weather API in two versions. The first one is just string like this: 2019-08-07 09:00:00 and like this: 1565209665. How do I change it to just the name of the day or day and month? For example Monday, August.

I tried something like this in few configurations but it works only in full version. If I cat something then it throws an error:

    var date = list.get(position).dt_txt
    val formatter = DateTimeFormatterBuilder()
        .appendPattern("yyyy-MM-dd HH:mm:ss").toFormatter()
    formatter.parse(date)
ikmazameti
  • 131
  • 3
  • 12
beginner992
  • 659
  • 1
  • 9
  • 28

6 Answers6

24

First API format:

val firstApiFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val date = LocalDate.parse("2019-08-07 09:00:00" , firstApiFormat)

Log.d("parseTesting", date.dayOfWeek.toString()) // prints Wednesday
Log.d("parseTesting", date.month.toString()) // prints August

Second API format:

val secondApiFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
val timestamp = 1565209665.toLong() // timestamp in Long


val timestampAsDateString = java.time.format.DateTimeFormatter.ISO_INSTANT
            .format(java.time.Instant.ofEpochSecond(timestamp))

Log.d("parseTesting", timestampAsDateString) // prints 2019-08-07T20:27:45Z


val date = LocalDate.parse(timestampAsDateString, secondApiFormat)

Log.d("parseTesting", date.dayOfWeek.toString()) // prints Wednesday
Log.d("parseTesting", date.month.toString()) // prints August
Ben Shmuel
  • 1,819
  • 1
  • 11
  • 20
19

This is really simple

val dateFormated = SimpleDateFormat("dd/MM/yyyy").format(trans.created_date.toDate())

I hope this works for everybody, thanks to https://www.datetimeformatter.com/how-to-format-date-time-in-kotlin/

AmrDeveloper
  • 3,826
  • 1
  • 21
  • 30
nosoythor
  • 231
  • 2
  • 7
7

Try this code to get dayOfWeek and month name

Code

To String Date

Method

fun getAbbreviatedFromDateTime(dateTime: String, dateFormat: String, field: String): String? {
    val input = SimpleDateFormat(dateFormat)
    val output = SimpleDateFormat(field)
    try {
        val getAbbreviate = input.parse(dateTime)    // parse input
        return output.format(getAbbreviate)    // format output
    } catch (e: ParseException) {
        e.printStackTrace()
    }

    return null
}

*How to use

val monthName=getAbbreviatedFromDateTime("2019-08-07 09:00:00","yyyy-MM-dd HH:mm:ss","MMMM")
    println("monthName--"+monthName)

    val dayOfWeek=getAbbreviatedFromDateTime("2019-08-07 09:00:00","yyyy-MM-dd HH:mm:ss","EEEE")
    println("dayOfWeek--"+dayOfWeek)

To Timemillis

Methods

 fun convertStringToCalendar( timeMillis: Long) {
    //get calendar instance
    val calendarDate = Calendar.getInstance()
    calendarDate.timeInMillis = timeMillis
    val month=getAbbreviatedFromDateTime(calendarDate,"MMMM");
    val day=getAbbreviatedFromDateTime(calendarDate,"EEEE");
    Log.d("parseTesting", month)// prints August
    Log.d("parseTesting",day)// prints Wednesday
}


fun getAbbreviatedFromDateTime(dateTime: Calendar, field: String): String? {
    val output = SimpleDateFormat(field)
    try {
        return output.format(dateTime.time)    // format output
    } catch (e: Exception) {
        e.printStackTrace()
    }

    return null
}

Use

 val timestamp = "1565209665".toLong()

    convertStringToCalendar(timestamp)
piet.t
  • 11,718
  • 21
  • 43
  • 52
Android Geek
  • 8,956
  • 2
  • 21
  • 35
  • Please not. When the questioner is already using Joda-Time (or perhaps java.time), suggesting `SimpleDateFormat` and `Calendar` is very bad advice. Those classes are poorly designed, which was why Joda-Time was developed, and they are also long outdated. – Ole V.V. Aug 08 '19 at 06:48
3

Try this

val stringDate="2019-08-07 09:00:00"

val dateFormat_yyyyMMddHHmmss = SimpleDateFormat(
    "yyyy-MM-dd HH:mm:ss", Locale.ENGLISH
)
val date = dateFormat_yyyyMMddHHmmss.parse(stringDate)
val calendar = Calendar.getInstance()
calendar.setTime(date)

val dayOfWeekString = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.ENGLISH)

Output:

dayOfWeekString : wednesday

val timeInMillis = 1565242471228
val calendar = Calendar.getInstance()
calendar.setTimeInMillis(timeInMillis)

val dayOfWeekString = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.ENGLISH)
Jignesh Mayani
  • 6,937
  • 1
  • 20
  • 36
  • Please not. When the questioner is already using Joda-Time (or perhaps java.time), suggesting `SimpleDateFormat` and `Calendar` is very bad advice. Those classes are poorly designed, which was why Joda-Time was developed, and they are also long outdated. – Ole V.V. Aug 08 '19 at 06:48
  • The questioner used [DateTimeFormatterBuilder](https://developer.android.com/reference/java/time/format/DateTimeFormatterBuilder) class, not `Joda-Time` & DateTimeFormatterBuilder is added in Added in API level 26 & that's why I gave `SimpleDateFormat` example – Jignesh Mayani Aug 08 '19 at 07:01
2
val parsedDate: String? = if(monthOfYear < 10 && dayOfMonth > 10){
                            "${dayOfMonth}/0${monthOfYear + 1}/${year}"

                        } else if(dayOfMonth < 10 && monthOfYear > 10) {
                            "0${dayOfMonth}/${monthOfYear + 1}/${year}"

                        } else if(dayOfMonth < 10 && monthOfYear < 10){
                            "0${dayOfMonth}/0${monthOfYear + 1}/${year}"
                        }else{
                            "0${dayOfMonth}/${monthOfYear + 1}/${year}"

                        }

                        date?.text = parsedDate

I tried different things but in Date picker this works for me in kotlin

Roman Alekseiev
  • 1,854
  • 16
  • 24
Jaaveeth
  • 21
  • 2
0

Example: 6/23/23 21:40

private val dateTimeFormat: DateFormat =
    DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)

fun getFormattedDateTime(): String = dateTimeFormat.format(Date().time)
kdan
  • 41
  • 3