I know this is a rather under-level question, if you may, but I'm having some trouble looking for code that I can put in my Windows forms. I just have three mere requirements:
I need the local time, which is EDT.
I also need the time in 24-hour format so it's easier to read.
Where to put the code in my Windows forms?
Since you've tagged your question with 'winforms' I'm assuming you're running on the .NET Framework. If so, I suggest starting here:
Coding Best Practices Using DateTime in the .NET Framework
... and also checking the documentation on DateTIme formatting here:
Custom Date and Time Format Strings
/* localtime example */
#include <stdio.h>
#include <time.h>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
http://www.cplusplus.com/reference/clibrary/ctime/localtime/
Related
I am looking for the UTC (from RFC3339 format) to IST conversion in C program. But I could not find any generic way to convert the time.
Here, I found the shell script to convert the UTC time (in RFC3339 format) to IST and I am trying to implement in C code.
From the script, I can't find the equivalent way for the statement
newdate=$(TZ=IST date -d "$formatT UTC-5:30") in C code.
So, I did time diff of -5:30 with the GMT time as shown in below snippet. But, it is not working as expected.
int main(int argc, char *argv[])
{
const char *utctime = "2019-07-24T11:47:33";
struct tm tm = {0};
char s[128] = {0};
if (NULL == (strptime(utctime, "%Y-%m-%dT%H:%M:%S", &tm))) {
printf("strptime failed\n");
}
printf("IST Time : %2d:%02d\n", ((tm.tm_hour-5)%24), tm.tm_min-30);
}
Kindly, guide me to do the task in C code that the script does.
Non-portable, linux:
struct tm time;
// fill appropriately
time_t utc = timegm(&time)
localtime_r(&utc, &time);
If your local time zone isn't IST, you need to change to before calling local time:
setenv("TZ", "IST-05:30:00", 1);
// ^ not entirely sure if this is correct, please verify yourself (*)
tzset();
Edit (following the comments): (*) Especially if daylight saving time (DST) has to be applied, the time zone string looks different; you find information about at tzset documentation. Possibly the server provides time zone information in a local file, then you might try :Asia/Kolkata as well.
You might retrieve current timezone with getenv first if you intend to restore it afterwards, complete example is shown at timegm documentation.
The portable way would now be to first set timezone to UTC, call mktime instead of timegm, then set timezone to IST and call localtime just as in non-portable version and finally restore local timezone (if intended/needed and you haven't already done so by setting it to IST).
I want to implement Unix milliseconds converter to human readable date format.
using this post https://stackoverflow.com/a/1657307/1979882 I found I can receive such string but I can't setup a time zone inside the code. The code uses only system time zone.
#include <stdio.h>
#include <time.h>
int main ( int argc, char *argv[] )
{
time_t now;
struct tm *lcltime;
now = time ( NULL );
lcltime = localtime ( &now );
printf ( "The time is %d:%d\n", lcltime->tm_hour, lcltime->tm_min );
return 0;
}
Is it possible to customize it?
EDIT
I need some Java-like method:
SimpleDateFormat df= new SimpleDateFormat("dd MMM hh:mm z",Locale.ENGLISH);
df.setTimeZone("Europe/London");
System.out.println("London Time " + df.format(System.currentTime()));
df.setTimeZone("Asia/Benjin");
System.out.println("Benjin Time " + df.format(System.currentTime()));
EDIT_2
I found I can setup time zone using setenv(...)
url
https://stackoverflow.com/a/1620451/1979882
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main (int argc, char *argv[])
{
struct tm *mt;
time_t mtt;
char ftime[10];
setenv("TZ", "PST8PDT", 1);
tzset();
mtt = time(NULL);
mt = localtime(&mtt);
strftime(ftime,sizeof(ftime),"%Z %H%M",mt);
printf("%s\n", ftime);
}
But in changes the system time zone. I need just time zone modification only inside my code.
You can change the argument to localtime based on the timezone difference required.
now += (time_t)(3600*TIME_DIFF_IN_HRS)
lcltime = localtime ( &now );
To be totally portable, you can get the current time zone by referring this post
I am trying to get UTC time as time_t.
Code below seems giving it correct but surprisingly prints local time only:
time_t mytime;
struct tm * ptm;
time ( &mytime ); // Get local time in time_t
ptm = gmtime ( &mytime ); // Find out UTC time
time_t utctime = mktime(ptm); // Get UTC time as time_t
printf("\nLocal time %X (%s) and UTC Time %X (%s)", mytime, ctime(&mytime), utctime, ctime(&utctime));
As we can see values of mytime and utctime we get are different.
However, when passed as parameters to ctime it converts them to same string.
Local time 55D0CB59 (Sun Aug 16 23:11:45 2015) and UTC Time 55D07E01
(Sun Aug 16 23:11:45 2015)
By definition the C time() function returns a time_t epoch time in UTC. So the code commented "//get the local time in time_t" is really getting UTC already, and the comment is incorrect.
From the Linux man-page:
time_t time(time_t *tloc);
time() returns the time as the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).
Giving the code:
#include <time.h>
...
time_t utc_now = time( NULL );
The ctime result is a static variable. Do not use ctime twice in the same print statement. Do it in two separate print statements.
If ctime is replaced with asctime, the same problem will arise as asctime also returns the result as a static variable.
That's exactly what the documented behavior is supposed to do:
Interprets the value pointed by timer as a calendar time and converts it to a C-string containing a human-readable version of the corresponding time and date, in terms of local time.
You probably want to use asctime instead.
ctime function returns a C string containing the date and time information in a human-readable format.
To get time in UTC you can use gettimeofday() (for Linux)-
struct timeval ptm;
gettimeofday(&ptm,NULL);
long int ms = ptm.tv_sec * 1000 + ptm.tv_usec / 1000;
And you can see function GetSystemTime in for windows.
Hope someone can help. I am fixing a problem in someone’s’ C code that was written a long time ago and he has since moved on.
The piece of code outputs the timestamp of a particular file. The code works fine when run on windows but when it is run on Linux it displays the Year incorrectly. The year is not displaying on linux, it shows 35222. Does anyone have any idea what is the problem here?
Thanks
Windows output:
Source file: test.dtl, Created: Mon, 27 May, 2013 at 16:13:20
Linux output:
Source file: test.dtl, Created: Mon, 27 May, 35222 at 16:13:20
The function in C code:
void SummaryReport ( report_t *report, char *dtlName)
{
LogEntry(L"SummaryReport entry\n");
int i;
wchar_t *rootStrType,*localStr,timeStr[48];
wchar_t fileBuff[64];
struct tm *timeVals;
timeVals = localtime (&logHdr.date);
wcsftime (timeStr,47,L"%a, %#d %b, %Y at %X",timeVals);
/* Print the header information */
DisplayReportFile (report);
ReportEntry (report,L" Filesystem Audit Summary Report\n\n");
ReportEntry (report,L"Source file: %s, Created: %ls\n\n",dtlName,timeStr);
ReportEntry (report,L"Server: %ls",srvrName);
…
}
Verified on a minimal example and it "works-for-me". Does this show the right time?
#include <wchar.h>
#include <time.h>
int main() {
wchar_t timeStr[48];
struct tm *timeVals;
time_t now = time(NULL);
timeVals = localtime(&now);
wcsftime(timeStr, 47, L"%a, %#d %b, %Y at %X", timeVals);
wprintf(timeStr);
return 0;
}
If yes, check the file itself - if you're sharing the filesystem, maybe there's some weird issue with the file timestamp itself? (or with understanding the fs metadata)
In case wcsftime() itself calls localtime(), insure the results of your call are not corrupted.
struct tm timeVals;
timeVals = *localtime (&logHdr.date);
wcsftime (timeStr,47,L"%a, %#d %b, %Y at %X", &timeVals);
localtime() saves its results in a static struct tm somewhere. The address (pointer) to that location is returned. Subsequent calls to localtime() or gmtime() alter the struct tm. I suspect the call to wcsftime() indirectly does that in Linux.
BTW: localtime() could return NULL, so safer code would check the localtime() return value.
Your may want to look into the localtime_s()
I need to convert time between timezones in C (on linux, so anything specific would do too).
I know my current time, local and UTC, I have the offset of the target time. I am trying to use mktime, gmtime, localtime and similar set of functions but still can't figure it out.
Thanks in advance.
As comments do not allow posting the code, posting as a separate answer.. If you know "local" time and "UTC" time, you can calculate the offset of the "other" time from your "local" time. Then you convert the struct tm into calendar time, add the desired number of seconds (being the offset of the target time), and convert it back to struct tm:
(edited to account for another scenario to use mktime's normalization)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
int main(int argc, char *argv) {
struct timeval tv_utc;
struct tm *local_tm, *other_tm;
/* 'synthetic' time_t to convert to struct tm for the other time */
time_t other_t_synt;
/* Other time is 1 hour ahead of local time */
int other_local_delta = 1*3600;
/* the below two lines are just to set local_tm to something */
gettimeofday(&tv_utc, NULL);
local_tm = localtime(&tv_utc.tv_sec);
printf("Local time: %s", asctime(local_tm));
#ifdef DO_NOT_WRITE_TO_LOCAL_TM
other_t_synt = mktime(local_tm) + other_local_delta;
#else
local_tm->tm_sec += other_local_delta;
/* mktime will normalize the seconds to a correct calendar date */
other_t_synt = mktime(local_tm);
#endif
other_tm = localtime(&other_t_synt);
printf("Other time: %s", asctime(other_tm));
exit(0);
}
You can use gmtime() and the tm structure to directly set this, provided you know the offsets.
If you know your local time and UTC, you know your local offset. Provided you also know the target offset, it's just a matter of setting tm_hour appropriate (and potentially flipping the day, too, if you go <0 or >23).
For some sample code, see this gmtime reference page. It shows offsetting based off time zone offsets.
Edit:
In response to the comments - you can also let mktime handle the shifting for you, which allows you to simplify this by converting back to a time_t. You can use something like:
time_t currentTime;
tm * ptm;
time ( ¤tTime );
ptm = gmtime ( &rawtime );
ptm->tm_hour += hours_to_shift;
ptm->tm_minutes += minutes_to_shift; // Handle .5 hr timezones this way
time_t shiftedTime = mktime( ptm );
// If you want to go back to a tm structure:
tm * pShiftedTm = gmtime( &shiftedTime );
In all likelyhood, your operating system provides some support for this.
In unix derived OSs you might want to look at the man pages for asctime, asctime_r, ctime, ctime_r, difftime, gmtime, gmtime_r, localtime, localtime_r, mktime, timegm.