androidandroid-date

How can i get current date and time in android and store it into string


Currently i am using the code below:

String  currentDateTimeString = DateFormat.getDateTimeInstance()
                        .format(new Date());

From this i am getting the output in the following format -

Jun 5, 2015 1:15:29 PM

But now i want the output in the format below-

2015-06-05 08:10:40 

It can be in 12 or 24 hour format.

I want current date time with above datetime format.

I have already use SimpleDateFormat but i am not able to get the above date time format with current date and time

So, how can i achieve this?


Solution

  • Update 01/Sept/2020 - Sample Kotlin DateUtilExtensions using Java SE 8

    @file:JvmName("DateUtilExtensions")
    
    package com.intigral.jawwytv.util.extensions
    
    import android.text.TextUtils
    import android.text.format.DateUtils
    import java.text.ParseException
    import java.text.SimpleDateFormat
    import java.time.Instant
    import java.time.LocalDate
    import java.time.LocalDateTime
    import java.time.ZoneId
    import java.time.ZoneOffset
    import java.time.format.DateTimeFormatter
    import java.util.Date
    import java.util.Locale
    import java.util.TimeZone
    
    const val PATTERN_YEAR = "yyyy"
    const val PATTERN_MONTH = "MMM"
    const val PATTERN_MONTH_FULL = "MMMM"
    const val PATTERN_DAY_OF_MONTH = "dd"
    const val PATTERN_DAY_OF_WEEK = "EEEE"
    const val PATTERN_TIME = "hh:mm a"
    const val PATTERN_TIME_24H = "HH:mm"
    const val PATTERN_SERVER_DATE = "yyyy-MM-dd"
    const val PATTERN_SERVER_DATE_TIME = "yyyy-MM-dd HH:mm:ss"
    const val PATTERN_START_WITH_MONTH = "MMM dd , yyyy"
    const val PATTERN_START_WITH_MONTH_NO_YEAR = "MMMM dd"
    const val PATTERN_START_WITH_DATE_NO_YEAR = "dd MMMM"
    const val PATTERN_START_WITH_MONTH_SHORT_NO_YEAR = "MMM dd"
    const val PATTERN_START_WITH_MONTH_WITH_TIME = "MMM dd, yyyy HH:mm:ss"
    const val PATTERN_START_WITH_MONTH_SMALL_NO_YEAR = "MMM dd"
    
    fun formatDate(pattern: String): String {
        val localDateTime = LocalDateTime.now()
        return localDateTime.format(DateTimeFormatter.ofPattern(pattern))
    }
    
    fun formatDate(localDateTime: LocalDateTime, pattern: String): String =
        localDateTime.format(DateTimeFormatter.ofPattern(pattern))
    
    fun formatDate(timeInMills: Long?, pattern: String): String =
        LocalDateTime.ofInstant(Instant.ofEpochMilli(timeInMills ?: 0), ZoneId.systemDefault())
            .format(DateTimeFormatter.ofPattern(pattern))
    
    fun todayToEpochMilli() =
        LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()
    
    fun isDateEqual(dateInMills: Long?, dateInMillsOther: Long?): Boolean {
        val systemDefault = ZoneOffset.systemDefault()
        val date = Instant.ofEpochMilli(dateInMills ?: 0).atZone(systemDefault).toLocalDate()
        val otherDate =
            Instant.ofEpochMilli(dateInMillsOther ?: 0).atZone(systemDefault).toLocalDate()
        return date.isEqual(otherDate)
    }
    
    fun convertDateString(inputPattern: String, outputPattern: String, stringDate: String): String? {
        val originalFormat = SimpleDateFormat(inputPattern, Locale.getDefault())
        val targetFormat = SimpleDateFormat(outputPattern, Locale.getDefault())
        val requiredFormat = originalFormat.parse(stringDate)
        return requiredFormat?.let { targetFormat.format(requiredFormat) }
    }
    
    fun getRelativeTimeSpanString(
        dateString: String,
        format: String = PATTERN_SERVER_DATE_TIME
    ): String? {
        if (!TextUtils.isEmpty(dateString)) {
            val simpleDateFormat = SimpleDateFormat(format, Locale.getDefault())
            simpleDateFormat.timeZone = TimeZone.getTimeZone(ZoneOffset.UTC)
            var date: Date? = null
            try {
                date = simpleDateFormat.parse(dateString)
            } catch (e: ParseException) {
                e.printStackTrace()
            }
    
            val epochTime = date!!.time
    
            val relTime = DateUtils.getRelativeTimeSpanString(
                epochTime,
                System.currentTimeMillis(),
                DateUtils.SECOND_IN_MILLIS
            )
    
            return relTime.toString()
        }
        return dateString
    }
    

    Initial Answer - use SimpleDateFormat

    Date today = new Date();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
    String dateToStr = format.format(today);
    System.out.println(dateToStr);