how to convert milliseconds to date format in android?

JavaAndroidAndroid DateDate

Java Problem Overview


I have milliseconds. I need it to be converted to date format of

example:

> 23/10/2011

How to achieve it?

Java Solutions


Solution 1 - Java

Just Try this Sample code:-

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;


public class Test {

/**
 * Main Method
 */
public static void main(String[] args) {
	System.out.println(getDate(82233213123L, "dd/MM/yyyy hh:mm:ss.SSS"));
}


/**
 * Return date in specified format.
 * @param milliSeconds Date in milliseconds
 * @param dateFormat Date format 
 * @return String representing date in specified format
 */
public static String getDate(long milliSeconds, String dateFormat)
{
    // Create a DateFormatter object for displaying date in specified format.
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);

    // Create a calendar object that will convert the date and time value in milliseconds to date. 
     Calendar calendar = Calendar.getInstance();
     calendar.setTimeInMillis(milliSeconds);
     return formatter.format(calendar.getTime());
}
}

Solution 2 - Java

Convert the millisecond value to Date instance and pass it to the choosen formatter.

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 
String dateString = formatter.format(new Date(dateInMillis)));

Solution 3 - Java

public static String convertDate(String dateInMilliseconds,String dateFormat) {
	return DateFormat.format(dateFormat, Long.parseLong(dateInMilliseconds)).toString();
}

Call this function

convertDate("82233213123","dd/MM/yyyy hh:mm:ss");

Solution 4 - Java

DateFormat.getDateInstance().format(dateInMS);

Solution 5 - Java

tl;dr

Instant.ofEpochMilli( myMillisSinceEpoch )           // Convert count-of-milliseconds-since-epoch into a date-time in UTC (`Instant`).
    .atZone( ZoneId.of( "Africa/Tunis" ) )           // Adjust into the wall-clock time used by the people of a particular region (a time zone). Produces a `ZonedDateTime` object.
    .toLocalDate()                                   // Extract the date-only value (a `LocalDate` object) from the `ZonedDateTime` object, without time-of-day and without time zone.
    .format(                                         // Generate a string to textually represent the date value.
        DateTimeFormatter.ofPattern( "dd/MM/uuuu" )  // Specify a formatting pattern. Tip: Consider using `DateTimeFormatter.ofLocalized…` instead to soft-code the formatting pattern.
    )                                                // Returns a `String` object.
    

java.time

The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes used by all the other Answers.

Assuming you have a long number of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z…

Instant instant = Instant.ofEpochMilli( myMillisSinceEpoch ) ;

To get a date requires a time zone. For any given moment, the date varies around the globe by zone.

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;  // Same moment, different wall-clock time.

Extract a date-only value.

LocalDate ld = zdt.toLocalDate() ;

Generate a String representing that value using standard ISO 8601 format.

String output = ld.toString() ;

Generate a String in custom format.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
String output = ld.format( f ) ;

Tip: Consider letting java.time automatically localize for you rather than hard-code a formatting pattern. Use the DateTimeFormatter.ofLocalized… methods.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Solution 6 - Java

try this code might help, modify it suit your needs

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date d = format.parse(fileDate);

Solution 7 - Java

i finally find normal code that works for me

Long longDate = Long.valueOf(date);

Calendar cal = Calendar.getInstance();
int offset = cal.getTimeZone().getOffset(cal.getTimeInMillis());
Date da = new Date(); 
da = new Date(longDate-(long)offset);
cal.setTime(da);

String time =cal.getTime().toLocaleString(); 
//this is full string        

time = DateFormat.getTimeInstance(DateFormat.MEDIUM).format(da);
//this is only time

time = DateFormat.getDateInstance(DateFormat.MEDIUM).format(da);
//this is only date

Solution 8 - Java

Short and effective:

DateFormat.getDateTimeInstance().format(new Date(myMillisValue))

Solution 9 - Java

public class LogicconvertmillistotimeActivity extends Activity {
    /** Called when the activity is first created. */
	 EditText millisedit;
	    Button   millisbutton;
	    TextView  millistextview;
	    long millislong;
	    String millisstring;
	    int millisec=0,sec=0,min=0,hour=0;
	    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        millisedit=(EditText)findViewById(R.id.editText1);
        millisbutton=(Button)findViewById(R.id.button1);
        millistextview=(TextView)findViewById(R.id.textView1);
        millisbutton.setOnClickListener(new View.OnClickListener() {        	
			@Override
			public void onClick(View v) {	
				millisbutton.setClickable(false);
				millisec=0;
				sec=0;
				min=0;
				hour=0;
				millisstring=millisedit.getText().toString().trim();
				millislong= Long.parseLong(millisstring);
				Calendar cal = Calendar.getInstance();
				SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
				if(millislong>1000){
					sec=(int) (millislong/1000);
					millisec=(int)millislong%1000;
					if(sec>=60){
						min=sec/60;
						sec=sec%60;
					}
					if(min>=60){
						hour=min/60;
						min=min%60;
					}
				}
				else
				{
					millisec=(int)millislong;
				}
				cal.clear();
				cal.set(Calendar.HOUR_OF_DAY,hour);
				cal.set(Calendar.MINUTE,min);
				cal.set(Calendar.SECOND, sec);
				cal.set(Calendar.MILLISECOND,millisec);
				String DateFormat = formatter.format(cal.getTime());
//				DateFormat = "";
				millistextview.setText(DateFormat);
			
			}
        });
    }
}

Solution 10 - Java

Coverting epoch format to SimpleDateFormat in Android (Java / Kotlin)

input: 1613316655000

output: 2021-02-14T15:30:55.726Z

In Java

long milliseconds = 1613316655000L;
Date date = new Date(milliseconds);
String mobileDateTime = Utils.getFormatTimeWithTZ(date);

//method that returns SimpleDateFormat in String

public static String getFormatTimeWithTZ(Date currentTime) {
    SimpleDateFormat timeZoneDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
    return timeZoneString = timeZoneDate.format(currentTime);
}

In Kotlin

var milliseconds = 1613316655000L
var date = Date(milliseconds)
var mobileDateTime = Utils.getFormatTimeWithTZ(date)

//method that returns SimpleDateFormat in String

fun getFormatTimeWithTZ(currentTime:Date):String {
  val timeZoneDate = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
  return timeZoneString = timeZoneDate.format(currentTime)
}

Solution 11 - Java

Latest solution in Kotlin:

private fun getDateFromMilliseconds(millis: Long): String {
    val dateFormat = "MMMMM yyyy"
    val formatter = SimpleDateFormat(dateFormat, Locale.getDefault())
    val calendar = Calendar.getInstance()
    
    calendar.timeInMillis = millis
    return formatter.format(calendar.time)
}

We need to add Locale as an argument of SimpleDateFormat or use LocalDate. Locale.getDefault() is a great way to let JVM automatically get the current location timezone.

Solution 12 - Java

    public static Date getDateFromString(String date) {

    Date dt = null;
    if (date != null) {
        for (String sdf : supportedDateFormats) {
            try {
                dt = new Date(new SimpleDateFormat(sdf).parse(date).getTime());
                break;
            } catch (ParseException pe) {
                pe.printStackTrace();
            }
        }
    }
    return dt;
}

public static Calendar getCalenderFromDate(Date date){
    Calendar cal =Calendar.getInstance();
    cal.setTime(date);return cal;

}
public static Calendar getCalenderFromString(String s_date){
    Date date = getDateFromString(s_date);
    Calendar cal = getCalenderFromDate(date);
    return cal;
}

public static long getMiliSecondsFromString(String s_date){
    Date date = getDateFromString(s_date);
    Calendar cal = getCalenderFromDate(date);
    return cal.getTimeInMillis();
}

Solution 13 - Java

public static String toDateStr(long milliseconds, String format)
{
    Date date = new Date(milliseconds);
    SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.US);
    return formatter.format(date);
}

Solution 14 - Java

I've been looking for an efficient way to do this for quite some time and the best I've found is:

DateFormat.getDateInstance(DateFormat.SHORT).format(new Date(millis));

Advantages:

  1. It's localized
  2. Been in Android since API 1
  3. Very simple

Disadvantages:

  1. Limited format options. FYI: SHORT is only a 2 digit year.
  2. You burn a Date object every time. I've looked at source for the other options and this is a fairly minor compared to their overhead.

You can cache the java.text.DateFormat object, but it's not threadsafe. This is OK if you are using it on the UI thread.

Solution 15 - Java

This is the easiest way using Kotlin

private const val DATE_FORMAT = "dd/MM/yy hh:mm"

fun millisToDate(millis: Long) : String {
    return SimpleDateFormat(DATE_FORMAT, Locale.US).format(Date(millis))
}

Solution 16 - Java

Use SimpleDateFormat for Android N and above. Use the calendar for earlier versions for example:

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        fileName = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss").format(new Date());
        Log.i("fileName before",fileName);
    }else{
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH,1);
        String zamanl =""+cal.get(Calendar.YEAR)+"-"+cal.get(Calendar.MONTH)+"-"+cal.get(Calendar.DAY_OF_MONTH)+"-"+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND);

        fileName= zamanl;
        Log.i("fileName after",fileName);
    }

Output:
fileName before: 2019-04-12-07:14:47  // use SimpleDateFormat
fileName after: 2019-4-12-7:13:12        // use Calender

Solution 17 - Java

fun convertLongToTimeWithLocale(){
    val dateAsMilliSecond: Long = 1602709200000
    val date = Date(dateAsMilliSecond)
    val language = "en"
    val formattedDateAsDigitMonth = SimpleDateFormat("dd/MM/yyyy", Locale(language))
    val formattedDateAsShortMonth = SimpleDateFormat("dd MMM yyyy", Locale(language))
    val formattedDateAsLongMonth = SimpleDateFormat("dd MMMM yyyy", Locale(language))
    Log.d("month as digit", formattedDateAsDigitMonth.format(date))
    Log.d("month as short", formattedDateAsShortMonth.format(date))
    Log.d("month as long", formattedDateAsLongMonth.format(date))
}

output:

month as digit: 15/10/2020
month as short: 15 Oct 2020 
month as long : 15 October 2020

You can change the value defined as 'language' due to your require. Here is the all language codes: Java language codes

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPattabi RamanView Question on Stackoverflow
Solution 1 - JavaUttamView Answer on Stackoverflow
Solution 2 - JavaPrince John WesleyView Answer on Stackoverflow
Solution 3 - JavaAtif MahmoodView Answer on Stackoverflow
Solution 4 - JavaaxpView Answer on Stackoverflow
Solution 5 - JavaBasil BourqueView Answer on Stackoverflow
Solution 6 - JavaingsaurabhView Answer on Stackoverflow
Solution 7 - JavaJohnView Answer on Stackoverflow
Solution 8 - JavaAlecsView Answer on Stackoverflow
Solution 9 - Javagaddam nagarajuView Answer on Stackoverflow
Solution 10 - JavaFaakhirView Answer on Stackoverflow
Solution 11 - JavaTop4oView Answer on Stackoverflow
Solution 12 - JavaRavindra RathourView Answer on Stackoverflow
Solution 13 - JavabackslashNView Answer on Stackoverflow
Solution 14 - JavaDustinView Answer on Stackoverflow
Solution 15 - JavaKenny OrellanaView Answer on Stackoverflow
Solution 16 - JavancinarView Answer on Stackoverflow
Solution 17 - JavaAtakan AkarView Answer on Stackoverflow