Get time in the Linux kernel and convert cost to timezone time

Source: Internet
Author: User
Tags local time

The following function, GET_TIME_STR, implements the ability to get local time in the kernel.

He first gets the UTC time and then translates the cost to time based on the system's time zone timezone,

The time is finally exported to the output buffer in the form of a string of "2014-11-02 21:14:08".

The return value of the function, which is the length of the output string.


#include <linux/time.h>

#include <linux/timex.h>

#include <linux/rtc.h>

int Get_time_str (char *output)
{
struct Timex Txc;
struct Rtc_time TM;


/* Gets the current UTC time */
Do_gettimeofday (& (Txc.time));


/* Adjust UTC time to local time */
TXC.TIME.TV_SEC-= sys_tz.tz_minuteswest * 60;


/* Calculate the number of months and days in the time to the TM */
Rtc_time_to_tm (TXC.TIME.TV_SEC,&TM);


return sprintf (Output, "%04d-%02d-%02d%02d:%02d:%02d"
, tm.tm_year+1900
, tm.tm_mon+1
, Tm.tm_mday
, Tm.tm_hour
, Tm.tm_min
, tm.tm_sec);
}


In fact, the system call Gettimeofday is implemented by Sys_gettimeofday ().

Sys_gettimeofday () is simply a copy of the time value obtained from the call to Do_gettimeofday () to the user state.

The code is as follows:

Asmlinkage long sys_gettimeofday (struct timeval __user *tv, struct timezone __user *tz)
{
if (likely (TV! = NULL)) {
struct Timeval KTV;
Do_gettimeofday (&KTV);
if (Copy_to_user (TV, &ktv, sizeof (KTV)))
Return-efault;
}


if (unlikely (tz! = NULL)) {
if (Copy_to_user (TZ, &sys_tz, sizeof (SYS_TZ)))
Return-efault;
}
return 0;
}

Get time in the Linux kernel and convert cost to timezone time

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.