Android中获得当前日期时间

来源:互联网 发布:在淘宝上如何买春药 编辑:程序博客网 时间:2024/05/22 15:41

1.  Kernel中获得当前时间

#include <linux/timer.h>
#include <linux/timex.h>
#include <linux/rtc.h>

static void get_time_now(void)
{
  struct timex  txc;
  struct rtc_time tm;
  do_gettimeofday(&(txc.time));
  rtc_time_to_tm(txc.time.tv_sec,&tm);
  printk(KERN_INFO "%d-%d-%d %d:%d:%d.%09lu\n",tm.tm_year+1900,tm.tm_mon+1, tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec,txc.time.tv_usec);
}

#include <linux/timer.h>

#include <linux/rtc.h>
static void get_time_now(void)
{
  struct timespec ts;
  struct rtc_time tm;

  getnstimeofday(&ts);
  rtc_time_to_tm(ts.tv_sec, &tm);
  printk(KERN_INFO " %d-%02d-%02d %02d:%02d:%02d.%09lu\n",
   tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
 tm.tm_hour, tm.tm_min, tm.tm_sec, ts.tv_nsec);
}

kernel/include/linux/rtc.h

struct rtc_time {
 int tm_sec;
 int tm_min;
 int tm_hour;
 int tm_mday;
 int tm_mon;
 int tm_year;
 int tm_wday;
 int tm_yday;
 int tm_isdst
}
kernel/include/linux/time.h

struct timespec {
 __kernel_time_t tv_sec;   /* seconds */
 long  tv_nsec;  /* nanoseconds */
};


struct timeval {
 __kernel_time_t  tv_sec;  /* seconds */
 __kernel_suseconds_t tv_usec; /* microseconds */
};

struct timezone {
 int tz_minuteswest; /* minutes west of Greenwich */
 int tz_dsttime; /* type of dst correction */
};

kernel/include/linux/timex.h
struct timex {
...
struct timeval time; 
...
}

 

2. Native C/C++

#include <time.h>
#include <sys/time.h>
char    str[20];

struct tm now;
 time_t t;
 time(&t);
 localtime_r(&t, &now);
 strftime(str, sizeof(str),"%Y-%m-%d-%H-%M-%S", &now);

ALOGD("%s", str);

 

struct tm {
  int     tm_sec;         /* seconds */
  int     tm_min;         /* minutes */
  int     tm_hour;        /* hours */
  int     tm_mday;        /* day of the month */
  int     tm_mon;         /* month */
  int     tm_year;        /* year */
  int     tm_wday;        /* day of the week */
  int     tm_yday;        /* day in the year */
  int     tm_isdst;       /* daylight saving time */

  long int tm_gmtoff;     /* Seconds east of UTC.  */
  const char *tm_zone;    /* Timezone abbreviation. 
}

 

3. Java

方法一

import    java.text.SimpleDateFormat;      
      
SimpleDateFormat    format1    =   new    SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");      
Date    curDate    =   new    Date(System.currentTimeMillis());       
String    str    =    format1.format(curDate);      

方法二

import android.text.format.Time
Time t=new Time(); // or Time t=new Time("GMT+8");
t.setToNow();
String s =String.format("%04d-%02d-%02d %02d:%02d:%02d",t.year,t.month,t.monthDay,t.hour,t.minute,t.second);

0 0
原创粉丝点击