在有年、月、日、时、分的情况下,如何根据设备配置的日期和时间正确格式化?
当前回答
这段代码将返回当前日期和时间:
public String getCurrDate()
{
String dt;
Date cal = Calendar.getInstance().getTime();
dt = cal.toLocaleString();
return dt;
}
其他回答
Try:
event.putExtra("startTime", "10/05/2012");
当你访问传递的变量时:
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(bundle.getString("startTime"));
我是这样使用的:
public class DateUtils {
static DateUtils instance;
private final DateFormat dateFormat;
private final DateFormat timeFormat;
private DateUtils() {
dateFormat = android.text.format.DateFormat.getDateFormat(MainApplication.context);
timeFormat = android.text.format.DateFormat.getTimeFormat(MainApplication.context);
}
public static DateUtils getInstance() {
if (instance == null) {
instance = new DateUtils();
}
return instance;
}
public synchronized static String formatDateTime(long timestamp) {
long milliseconds = timestamp * 1000;
Date dateTime = new Date(milliseconds);
String date = getInstance().dateFormat.format(dateTime);
String time = getInstance().timeFormat.format(dateTime);
return date + " " + time;
}
}
这段代码将返回当前日期和时间:
public String getCurrDate()
{
String dt;
Date cal = Calendar.getInstance().getTime();
dt = cal.toLocaleString();
return dt;
}
回到2016年,当我想自定义格式(不是根据设备配置,如你所问…)我通常使用字符串资源文件:
在strings.xml:
<string name="myDateFormat"><xliff:g id="myDateFormat">%1$td/%1$tm/%1$tY</xliff:g></string>
在活动:
Log.d(TAG, "my custom date format: "+getString(R.string.myDateFormat, new Date()));
这对于新的日期绑定库的发布也很有用。
我可以在布局文件中有这样的东西:
<TextView
android:id="@+id/text_release_date"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:padding="2dp"
android:text="@{@string/myDateFormat(vm.releaseDate)}"
tools:text="0000"
/>
在java类中:
MovieDetailViewModel vm = new MovieDetailViewModel();
vm.setReleaseDate(new Date());
这个代码为我工作!
Date d = new Date();
CharSequence s = android.text.format.DateFormat.format("MM-dd-yy hh-mm-ss",d.getTime());
Toast.makeText(this,s.toString(),Toast.LENGTH_SHORT).show();
推荐文章
- 警告:API ' variable . getjavacompile()'已过时,已被' variable . getjavacompileprovider()'取代
- 安装APK时出现错误
- 碎片中的onCreateOptionsMenu
- TextView粗体通过XML文件?
- 如何使线性布局的孩子之间的空间?
- 解析日期字符串并更改格式
- DSL元素android.dataBinding。enabled'已过时,已被'android.buildFeatures.dataBinding'取代
- ConstraintLayout:以编程方式更改约束
- PANIC: AVD系统路径损坏。检查ANDROID_SDK_ROOT值
- 如何生成字符串类型的buildConfigField
- Recyclerview不调用onCreateViewHolder
- Android API 21工具栏填充
- Android L中不支持操作栏导航模式
- Java SimpleDateFormat("yyyy-MM-dd' t ' hh:mm:ss' z '")给出的时区为IST
- 在Java中转换字符串到日历对象