473,699 Members | 2,838 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

using localtime

Raj
Hi

I'm very new to C and am trying to get the time a month ago in the format
mmyy.

What I have tried so far is:

char *last_mth;
size_t maxsize = 4;
struct tm *timeptr = localtime(time( 0));
strftime(last_m th, maxsize, "%m%y", timeptr);

to get the current mmyy, but I don't know how to access the tm struct so
that I can decrement the month.

I know this is the simplest of things to do, but I haven't found it in the
FAQ. If this is a silly request, please let me know. I'm off to look in
tutorials in case they can tell me there.

Thanks in advance for any help provided.

Regards,
--
Raj Kothary :: one|concept
http://www.oneconcept.net
ra*@oneconcept. net
+ 44 (0)79 5647 2746

oneconcept limited :: 17 York Avenue, Stanmore, Middlesex HA7 2HT

Confidentiality notice:
The information transmitted in this email and/or any attached document(s) is
confidential and intended only for the person or entity to which it is
addressed and may contain privileged material. Any review, retransmission,
dissemination or other use of, or taking of any action in reliance upon this
information by persons or entities other than the intended recipient is
prohibited. If you received this in error, please contact the sender and
delete the material from any computer.
Nov 14 '05 #1
5 2630
Raj wrote:
I'm very new to C and am trying to get the time a month ago in the format
mmyy.

What I have tried so far is:

char *last_mth;
size_t maxsize = 4;
struct tm *timeptr = localtime(time( 0));
strftime(last_m th, maxsize, "%m%y", timeptr);

to get the current mmyy, but I don't know how to access the tm struct so
that I can decrement the month.


These are the members of struct tm:

int tm_sec; // seconds after the minute -- [0, 60]
int tm_min; // minutes after the hour -- [0, 59]
int tm_hour; // hours since midnight -- [0, 23]
int tm_mday; // day of the month -- [1, 31]
int tm_mon; // months since January -- [0, 11]
int tm_year; // years since 1900
int tm_wday; // days since Sunday -- [0, 6]
int tm_yday; // days since January 1 -- [0, 365]
int tm_isdst; // Daylight Saving Time flag

So to decrease the month value you simply do this:
timeptr->tm_mon -= 1;
The case where tm_mon is already zero is left as an exercise...
Christian
Nov 14 '05 #2
Raj wrote:
Hi

I'm very new to C and am trying to get the time a month ago in the format
mmyy.

What I have tried so far is:

char *last_mth;
size_t maxsize = 4;
struct tm *timeptr = localtime(time( 0));


Why did you ignore the compiler's complaint about
this line? I was going to write you a nice explanation
of what was going wrong and how to fix it -- in fact, I
actually did write it -- but decided it would be wasted
on someone who won't even accept help from his compiler.

Please work on your code at least until the compiler
accepts it without complaint, or until you get a complaint
that you find baffling. Then post a minimal, complete
program demonstrating the problem at hand -- once you've
given evidence of having made an honest try, I for one
will be happy to give help.

--
Eric Sosman
es*****@acm-dot-org.invalid
Nov 14 '05 #3
Raj wrote:
Hi

I'm very new to C and am trying to get the time a month ago in the format mmyy.

What I have tried so far is:

char *last_mth;
size_t maxsize = 4;
struct tm *timeptr = localtime(time( 0));
strftime(last_m th, maxsize, "%m%y", timeptr);
There are many mistakes with your code. Firstly, you pass an
uninitialized pointer (last_mth) to strftime. Next, maxsize should be
at least 5, strings in C are terminated with a nul character, you need
to leave room for strftime to add this. The time function returns a
value of type time_t, localtime takes a pointer to time_t, you are
passing a time_t to localtime, not a pointer.

Here is a working version (without error checking):

#include <stdio.h>
#include <time.h>

int main (void) {
char last_month[10];
size_t length = sizeof(last_mon th)/sizeof(last_mon th[0]);
time_t mytime = time(NULL);
struct tm *timeptr = localtime(&myti me);

strftime(last_m onth, length, "%m%y", timeptr);
printf("%s\n", last_month);
return 0;
}
to get the current mmyy, but I don't know how to access the tm struct so that I can decrement the month.
The tm struct contains members tm_mday, tm_mon, and tm_year (among
others) which are integers representing day of month, month of year,
and year respectively, month is zero based. So, to answer your
question, just decrement the tm_mon member of an initialized struct tm:

timeptr->tm_mon--;

Of course you will want to check if the current month is 0 (January)
and if so you probably want to set the month to 11 (December) and
decrement the year. Then you have to decide what to do if the day in
the current month does not exist in the new month, etc.
I know this is the simplest of things to do, but I haven't found it in the FAQ. If this is a silly request, please let me know. I'm off to look in tutorials in case they can tell me there.
You should try taking a look at your library documentation or pick up a
good C book.
Thanks in advance for any help provided.

Regards,
--
Raj Kothary :: one|concept
http://www.oneconcept.net
ra*@oneconcept. net
+ 44 (0)79 5647 2746


Rob Gamble

Nov 14 '05 #4


Raj wrote:
Hi

I'm very new to C and am trying to get the time a month ago in the format
mmyy.

What I have tried so far is:

char *last_mth;
size_t maxsize = 4;
struct tm *timeptr = localtime(time( 0));
strftime(last_m th, maxsize, "%m%y", timeptr);

to get the current mmyy, but I don't know how to access the tm struct so
that I can decrement the month.


Function localtime takes a pointer argument. Also, you
need to first check the value returned from function time
to make sure that the value represents time, then use a
pointer to the time_t value should it represent a valid time.
To reduce the month after the function localtime call, use:
timeptr->tm_mon--; or timeptr->tm_mon -= 1;
Then use function mktime to normalize the values in the struct
tm. You can put all this in a function. Example below.

#include <stdio.h>
#include <time.h>

char *MinusOneMonth( time_t tvalue)
{
struct tm *t;
static char stime[5];

if(tvalue != (time_t)-1)
{
t = localtime(&tval ue);
t->tm_mon--;
if((tvalue = mktime(t)) != (time_t)-1)
{
int tmp = t->tm_year%100;
sprintf(stime," %02d%02d",t->tm_mon+1,tmp );
}
}
return tvalue==(time_t )-1?NULL:stime;
}

int main(void)
{
char *s;
struct tm *t;
time_t now = time(NULL);

if((s = MinusOneMonth(n ow)) != NULL)
{
printf("Now is: %sOne month ago in "
"format(mmy y) is: \"%s\" \n",ctime(&now) , s);
puts("\nTest for the month Jan\n");
t = localtime(&now) ;
t->tm_mon = 0; /* Makes it month January */
now = mktime(t);
if((s = MinusOneMonth(n ow)) != NULL)
printf("Now is: %sOne month ago "
"in format(mmyy) is: \"%s\"\n",ctime (&now), s);
else puts("Time is not available");
}
else puts("Time is not available");
return 0;
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #5

Al Bowers wrote:
Raj wrote:
Hi

I'm very new to C and am trying to get the time a month ago in the format mmyy.

What I have tried so far is:

char *last_mth;
size_t maxsize = 4;
struct tm *timeptr = localtime(time( 0));
strftime(last_m th, maxsize, "%m%y", timeptr);

to get the current mmyy, but I don't know how to access the tm struct so that I can decrement the month.

Function localtime takes a pointer argument. Also, you
need to first check the value returned from function time
to make sure that the value represents time, then use a
pointer to the time_t value should it represent a valid time.
To reduce the month after the function localtime call, use:
timeptr->tm_mon--; or timeptr->tm_mon -= 1;
Then use function mktime to normalize the values in the struct
tm. You can put all this in a function. Example below.

#include <stdio.h>
#include <time.h>

char *MinusOneMonth( time_t tvalue)
{
struct tm *t;
static char stime[5];

if(tvalue != (time_t)-1)
{
t = localtime(&tval ue);
t->tm_mon--;
if((tvalue = mktime(t)) != (time_t)-1)
{
int tmp = t->tm_year%100;
sprintf(stime," %02d%02d",t->tm_mon+1,tmp );
}
}
return tvalue==(time_t )-1?NULL:stime;
}

int main(void)
{
char *s;
struct tm *t;
time_t now = time(NULL);

if((s = MinusOneMonth(n ow)) != NULL)
{
printf("Now is: %sOne month ago in "
"format(mmy y) is: \"%s\" \n",ctime(&now) , s);
puts("\nTest for the month Jan\n");
t = localtime(&now) ;
t->tm_mon = 0; /* Makes it month January */
now = mktime(t);
if((s = MinusOneMonth(n ow)) != NULL)
printf("Now is: %sOne month ago "
"in format(mmyy) is: \"%s\"\n",ctime (&now), s);
else puts("Time is not available");
}
else puts("Time is not available");
return 0;
}


This will produce incorrect results if the current day of the month
does not exist in the previous month, for example if the current day is
Dec 31, or Mar 30, etc.
--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapi dsys.com (remove the x to send email)
http://www.geocities.com/abowers822/


Rob Gamble

Nov 14 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2156
by: Dariusz | last post by:
Can anyone help me out on how to get this time dependent code to work. I want it to display a greeting depending on the hour of the day (I'm trying to convert my own Perl code to PHP with no luck on this one). I want it to use the time of the local computer rather than the server. Thanks Dariusz <?PHP
1
2043
by: Udo Melis | last post by:
udo:/usr/lib/cgi-bin# python Python 2.3.4 (#2, Jul 28 2004, 09:39:34) on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from time import localtime Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/lib/cgi-bin/time.py", line 3, in ? NameError: name 'localtime' is not defined >>>
2
5027
by: Raskolnikow | last post by:
Hi! I have a very simple problem with itoa() or the localtime(...). Sorry, if it is too simple, I don't have a proper example. Please have a look at the comments. struct tm *systime; time_t currentTime; char day; char month;
3
9461
by: david | last post by:
I used the localtime() function in the following code snippet: .... tm = localtime(&ps->date); printf("---------------------\n"); printf("Date: %d/%02d/%02d %02d:%02d:%02d\n", 1900 + tm->tm_year, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); ....
1
24527
by: KW | last post by:
Hi all, Appreciate if someone can help me out on this. Currently, I have a tm structure holding information of the UTC time, which is very likely to be in the past, meaning not the current time. So, let's say I'm in CST(-6) now, and I want to know the equivalent local time of that tm structure, how do I do that taking into consideration daylight savings adjustments?
7
3511
by: Peter Jansson | last post by:
Dear group, I have been struggling to get a simple program for inserting and extracting std::tm objects to/from streams to work. The code below tries to read a std::tm object from a std::istringstream but fails to do so, could anybody see what is wrong with the code? (Output follows the code.) I fear that I have not completely grasped how the time_getXXX methods should be used in the operator<< ? With best regards,
2
4682
by: janama | last post by:
Hi all, Using wx When adding a second timer as i have the first, the second timer adding stops the first timer (updating or stops?) . In this example im updating a uptime and localtime label. It works fine for displaying the last "self.startTimer2()" called. But prevents the previous self.startTimer1() from running . Im doing something fundamentally wrong i guess?
16
3049
by: maruk2 | last post by:
I have some old data files with old timestamps, where timestmap=time(NULL), some of them date back to the year 1999. I want to my code to print the timestamps and each one to include hour:minute:second as of the corresponding old day. The only routine for this job seems to be localtime(timestmap) - this is Windows Vista, Visual Studio 2005 C++.
1
1799
by: maruk2 | last post by:
I have some old data files with old timestamps, where timestmap=time(NULL), some of them date back to the year 1999. I want my code to print the timestamps and each one to include hour:minute:second as of the corresponding old day. The only routine for this job seems to be localtime(timestmap) - this is Windows Vista, Visual Studio 2005 C++.
0
8685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8612
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9171
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9032
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8905
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8880
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6532
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2342
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.