120

我有毫秒。我需要将其转换为日期格式

例子:

23/10/2011

如何实现?

4

17 回答 17

228

试试这个示例代码:-

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());
}
}
于 2011-10-31T12:59:20.373 回答
92

毫秒值转换为Date实例并将其传递给选择的格式化程序。

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 
String dateString = formatter.format(new Date(dateInMillis)));
于 2011-10-31T12:41:39.460 回答
39
public static String convertDate(String dateInMilliseconds,String dateFormat) {
    return DateFormat.format(dateFormat, Long.parseLong(dateInMilliseconds)).toString();
}

调用这个函数

convertDate("82233213123","dd/MM/yyyy hh:mm:ss");
于 2012-12-09T15:46:50.890 回答
13
DateFormat.getDateInstance().format(dateInMS);
于 2013-03-01T10:50:51.163 回答
13
于 2018-03-20T07:31:44.837 回答
11

试试这个代码可能会有所帮助,修改它以满足您的需要

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date d = format.parse(fileDate);
于 2011-10-31T12:32:44.560 回答
8

我终于找到适合我的正常代码

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
于 2012-02-08T16:18:38.647 回答
5

简短而有效:

DateFormat.getDateTimeInstance().format(new Date(myMillisValue))
于 2015-02-12T09:28:58.233 回答
4
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);

            }
        });
    }
}
于 2012-11-01T06:39:38.313 回答
3

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)
}
于 2021-02-17T06:16:19.743 回答
2
    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();
}
于 2016-08-18T07:02:29.607 回答
2
public static String toDateStr(long milliseconds, String format)
{
    Date date = new Date(milliseconds);
    SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.US);
    return formatter.format(date);
}
于 2017-05-19T11:20:16.167 回答
2

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.

于 2019-08-20T15:22:08.437 回答
2

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))
}
于 2020-07-25T05:18:16.393 回答
2

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.

于 2021-12-15T07:52:09.650 回答
0

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

于 2019-04-12T07:43:50.843 回答
0
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

于 2020-10-22T18:12:20.420 回答