Date / time not right in C


5 posts
by paulcpaulc » Tue Jul 10, 2012 9:41 pm
I think my Debian image uses network to set time/date

If I type "date" command then I get valid date/time, eg...
Tue Jul 10 22:38:40 BST 2012

Yet the C library functions like...

timeinfo = localtime(&rawtime) ;
strftime(strResponse,128,"%H:%M:%S %d-%b-%Y",timeinfo);

returns the "zero" time of 01:00:00 01-Jan-1970

Does anyone have an idea why this is please?


Thanks,
Paul.
Posts: 15
Joined: Sun May 27, 2012 12:06 pm
by SN » Tue Jul 10, 2012 9:44 pm
have you checked the numeric value of rawtime or the contents of timeinfo - they're probably ending up as zero
Steve N – binatone mk4->intellivision->zx81->spectrum->cbm64->cpc6128->520stfm->pc->raspi ?
User avatar
Posts: 1009
Joined: Mon Feb 13, 2012 8:06 pm
Location: Romiley, UK
by gordon@drogon.net » Wed Jul 11, 2012 8:19 am
paulcpaulc wrote:I think my Debian image uses network to set time/date

If I type "date" command then I get valid date/time, eg...
Tue Jul 10 22:38:40 BST 2012

Yet the C library functions like...

timeinfo = localtime(&rawtime) ;
strftime(strResponse,128,"%H:%M:%S %d-%b-%Y",timeinfo);

returns the "zero" time of 01:00:00 01-Jan-1970

Does anyone have an idea why this is please?


Thanks,
Paul.


Probably stating the obvious but did you actually set rawtime? ie. did you do:

rawtime = time (NULL) ;

beforehand?

This:

Code: Select all
#include <stdio.h>
#include <time.h>

int main ()
{
  struct tm *timeinfo ;
  time_t rawtime ;
  char strResponse [128] ;

  rawtime = time (NULL) ;
  timeinfo = localtime(&rawtime) ; 
  strftime(strResponse,128,"%H:%M:%S %d-%b-%Y",timeinfo); 

  printf ("%s\n", strResponse) ;
}

works for me:
Code: Select all
gordon @ pi0: cc -o x x.c
gordon @ pi0: ./x
09:17:26 11-Jul-2012

-Gordon
--
Gordons projects: https://projects.drogon.net/
User avatar
Posts: 1487
Joined: Tue Feb 07, 2012 2:14 pm
Location: Devon, UK
by paulcpaulc » Wed Jul 11, 2012 8:06 pm
Sheesh, a million lines of C under my belt (albeit 10 years ago+) and I make a newbie error like that Gordon.

Still I'm man enough to own up to that newbie error.

Next time, more thought before posting :-)


Thanks all,
Paul.
Posts: 15
Joined: Sun May 27, 2012 12:06 pm
by gordon@drogon.net » Wed Jul 11, 2012 8:37 pm
paulcpaulc wrote:Sheesh, a million lines of C under my belt (albeit 10 years ago+) and I make a newbie error like that Gordon.

Still I'm man enough to own up to that newbie error.

Next time, more thought before posting :-)


Thanks all,
Paul.


Ah well - things that trip me up in that vein is trying to do

timeinfo = localtime(time (NULL)) ;

Glad your going now though!

-Gordon
--
Gordons projects: https://projects.drogon.net/
User avatar
Posts: 1487
Joined: Tue Feb 07, 2012 2:14 pm
Location: Devon, UK