简体   繁体   中英

how to convert milliseconds to date format in android?

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

example:

23/10/2011

How to achieve it?

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());
}
}

I hope this help...

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)));
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");
DateFormat.getDateInstance().format(dateInMS);

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?

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);

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

简短有效:

DateFormat.getDateTimeInstance().format(new Date(myMillisValue))
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);

            }
        });
    }
}
    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();
}
public static String toDateStr(long milliseconds, String format)
{
    Date date = new Date(milliseconds);
    SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.US);
    return formatter.format(date);
}

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.

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)
}

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))
}

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

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

You can construct java.util.Date on milliseconds. And then converted it to string with java.text.DateFormat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM