【发布时间】:2011-12-18 17:13:25
【问题描述】:
我有几毫秒。 我需要将其转换为
的日期格式示例:
23/10/2011
如何实现?
【问题讨论】:
标签: java android android-date date
我有几毫秒。 我需要将其转换为
的日期格式示例:
23/10/2011
如何实现?
【问题讨论】:
标签: java android android-date date
试试这个示例代码:-
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());
}
}
【讨论】:
java.util.Date、java.util.Calendar 和 java.text.SimpleDateFormat 等麻烦的旧日期时间类现在已被 java.time 类所取代。在ThreeTen-Backport 项目中,许多java.time 功能被反向移植到Java 6 和Java 7。在ThreeTenABP 项目中进一步适用于早期的Android。见How to use ThreeTenABP…。
将 毫秒 值转换为 Date 实例并将其传递给选择的格式化程序。
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();
}
调用这个函数
convertDate("82233213123","dd/MM/yyyy hh:mm:ss");
【讨论】:
DateFormat.getDateInstance().format(dateInMS);
【讨论】:
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 类来取代所有其他 Answers 使用的麻烦的旧的旧日期时间类。
假设您有一个long 自 1970 年第一刻(UTC,1970-01-01T00:00:00Z)的纪元参考以来的毫秒数……
Instant instant = Instant.ofEpochMilli( myMillisSinceEpoch ) ;
获取日期需要时区。对于任何给定的时刻,日期在全球范围内因地区而异。
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
提取仅日期值。
LocalDate ld = zdt.toLocalDate() ;
使用标准 ISO 8601 格式生成一个表示该值的字符串。
String output = ld.toString() ;
以自定义格式生成字符串。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
String output = ld.format( f ) ;
提示:考虑让 java.time 自动为您本地化,而不是硬编码格式模式。使用DateTimeFormatter.ofLocalized… 方法。
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。 Hibernate 5 & JPA 2.2 支持 java.time。
从哪里获取 java.time 类?
【讨论】:
试试这个代码可能会有所帮助,修改它以满足您的需要
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date d = format.parse(fileDate);
【讨论】:
我终于找到适合我的正常代码
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);
}
});
}
}
【讨论】:
在 Android (Java / Kotlin) 中将 epoch 格式转换为 SimpleDateFormat
输入:1613316655000
输出:2021-02-14T15:30:55.726Z
在 Java 中
long milliseconds = 1613316655000L;
Date date = new Date(milliseconds);
String mobileDateTime = Utils.getFormatTimeWithTZ(date);
//以String形式返回SimpleDateFormat的方法
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);
}
在科特林中
var milliseconds = 1613316655000L
var date = Date(milliseconds)
var mobileDateTime = Utils.getFormatTimeWithTZ(date)
//以String形式返回SimpleDateFormat的方法
fun getFormatTimeWithTZ(currentTime:Date):String {
val timeZoneDate = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
return timeZoneString = timeZoneDate.format(currentTime)
}
【讨论】:
SimpleDateFormat和朋友。看看您是否可以使用desugaring 或将ThreeTenABP 添加到您的Android 项目中,以便使用现代Java 日期和时间API 的java.time。使用起来感觉好多了。
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);
}
【讨论】:
我一直在寻找一种有效的方法来做到这一点,我发现最好的方法是:
DateFormat.getDateInstance(DateFormat.SHORT).format(new Date(millis));
优点:
缺点:
您可以缓存 java.text.DateFormat 对象,但它不是线程安全的。如果你在 UI 线程上使用它就可以了。
【讨论】:
这是使用 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))
}
【讨论】:
SimpleDateFormat类。至少不是第一选择。而且不是没有任何保留。今天我们在java.time, the modern Java date and time API, 和它的DateTimeFormatter 中做得更好。是的,您可以在 Android 上使用它。对于较旧的 Android,请使用脱糖或查看 How to use ThreeTenABP in Android Project。
hh?请在此处检查大写和小写之间的区别。
return Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern(DATE_FORMAT, Locale.US))。是的,它更长,因为它提供了更多关于正在发生的事情的信息,所以这是一个优势。
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)
}
我们需要添加 Locale 作为 SimpleDateFormat 的参数或使用 LocalDate。 Locale.getDefault() 是让 JVM 自动获取当前位置时区的好方法。
【讨论】:
对 Android N 及更高版本使用 SimpleDateFormat。使用早期版本的日历 例如:
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);
}
输出:
之前的文件名:2019-04-12-07:14:47 // 使用 SimpleDateFormat
之后的文件名:2019-4-12-7:13:12 // 使用日历
【讨论】:
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))
}
输出:
month as digit: 15/10/2020
month as short: 15 Oct 2020
month as long : 15 October 2020
您可以根据需要更改定义为“语言”的值。这是所有语言代码: Java language codes
【讨论】:
SimpleDateFormat和朋友。看看您是否可以使用 desugaring 或将 ThreeTenABP 添加到您的 Android 项目中,以便使用现代 Java 日期和时间 API java.time。使用起来感觉好多了。