time = “20160709093428”;
这是我的时间字符串 我想实现的是把它打印出yyyy/MM/dd HH:mm:ss 或者"yyyy年MM月dd日HH时mm分ss秒"的形式,下面是我的代码
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");//("yyyy年MM月dd日HH时mm分ss秒")
Date date = simpleDateFormat.parse(time);
Log.i("系统时间", String.valueOf(date));
现在我的问题是如果我new SimpleDateFormat("yyyyMMddHHmmss")里面是("yyyy年MM月dd日HH时mm分ss秒")或者yyyy/MM/dd HH:mm:ss 的格式就会报错System.err: java.text.ParseException: Unparseable date: "20160709093947" (at offset 14) 只能是"yyyyMMddHHmmss"的形式然后打印出来的效果是Sat Jul 09 09:40:50 格林尼治标准时间+0800 2016这样的 请问怎样才能得到我想要的效果?
时间戳就是如1377216000000 这种格式,在mysql数据库中会经常用到把时间转换成时间戳或把时间戳转换成日期格式了,下面是时间戳操作转换方法:
一、原理
时间戳的原理是把时间格式转为十进制格式,这样就方便时间的计算
如: 2013年08月23日 转化后是 1377216000000
二、步骤
1、创建 DateUtilsl类。
代码如下:
importjava.text.ParseException;
importjava.text.SimpleDateFormat;
importjava.util.Date;
/*
* @author Msquirrel
*/
public class DateUtils {
privateSimpleDateFormat sf = null;
/*获取系统时间 格式为:"yyyy/MM/dd "*/
public static String getCurrentDate() {
Date d = newDate();
sf = newSimpleDateFormat("yyyy年MM月dd日");
returnsf.format(d);
}
/*时间戳转换成字符窜*/
public static String getDateToString(long time) {
Date d = newDate(time);
sf = newSimpleDateFormat("yyyy年MM月dd日");
returnsf.format(d);
}
/*将字符串转为时间戳*/
public static long getStringToDate(String time) {
sdf = newSimpleDateFormat("yyyy年MM月dd日");
Date date = newDate();
try{
date = sdf.parse(time);
} catch(ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
returndate.getTime();
}
2、在对应使用的地方调用。
代码如下:
DateUtils.getCurrentDate(); //获取系统当前时间
DateUtils.getDateToString(时间戳); //时间戳转为时间格式
DateUtils.getStringToDate("时间格式");//时间格式转为时间戳.
之前写的一个小demo,希望能帮到你
package com.example.administrator.data;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class MainActivity extends AppCompatActivity {
private TextView time;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = (TextView) findViewById(R.id.time);;
SimpleDateFormat myFmt1=new SimpleDateFormat("yy/MM/dd");
Date date =new Date();
long sd=1345185923140L;
Date date1=new Date(sd);
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date1);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
time.setText(format.format(gc.getTime()));
}
}