C++ Setting the Date for localtime - c++

I have a piece of C++ code in C++11 that uses localtime function (doc) to get the time. If the day is my birthday, it returns a birthday message.
std::string message = getDailyMessage();
I would now like to make a unit test that determines if the code outputs the right value on my birthday and not on my birthday. Is there a way to programmatically set the value returned by localtime before two adjacent calls? Is it possible to do without mucking around with the actual system time?
setTime(NOT_BIRTHDAY);
EXPECT_STREQ(NOT_BIRTHDAY_MESSAGE, getDailyMessage());
setTime(BIRTHDAY);
EXPECT_STREQ(BIRTDAY_MESSAGE, getDailyMessage());

You could make getDailyMessage take the time by parameter. This makes unit testing a breeze and adds the flexibility of being able to use it in other contexts. For instance you could use it to print the yesterday's message.

Related

Delete record by time in InfluxDB-CXX

Reference: https://github.com/offa/influxdb-cxx
It is easy to delete record by time using CLI interface,
delete from imagetable where time='2022-11-16T19:42:41.945508272Z'
but I am not able to figure out how to do the same with influxdb-cxx. i.e. not able to access the time through C++ interface.
e.g. Tags can be accessed with function points[0].getTags() but how to access the time ?
Have already tried to access it with points[0].getTimestamp() but not able to print it in this format in C++ 2022-11-17T03:37:25.934547412Z
can anyone please help ? Thanks in advance.
In influxdb-cxx you can use InfluxDB::execute method to execute InfluxQL statements like from your example for CLI interface. Regarding timestamps, they are saved as std::chrono::time_point<std::chrono::system_clock> (source) in the library's Point class, which denotes Unix (epoch) time excluding leap seconds (which is what timestamps in InfluxDB represent). Your example uses RFC3339 notation to provide timestamp, but InfluxQL also directly understands "nanosecond count since epoch" notation for it (example). So, it isn't necessary to represent Point's timepoint in RFC3339 notation to use it in execute command (which is possible, but harder and reduntant), you can just use standard C++ chrono library functions to get nanoseconds since epoch for given timepoint. Example:
using namespace std::chrono;
auto nsEpoch = duration_cast<nanoseconds>(points[0].getTimestamp().time_since_epoch()).count();
idb->execute("delete from imagetable where time=" + std::to_string(nsEpoch));

How to deal with time in C++?

Basically I need to write a program that will ask the user to enter arrival and departure time in the 24 hour format and it needs to calculate the difference between them.
I know how to do everything else, but i'm not sure how to make it so that it lets you enter the time.
You can use std::get_time to parse the input into a std::tm structure. You can use std::chrono::system_clock::from_time_t to convert the std::tm object into a time point. You can subtract the time points to calculate the difference.
In C++20, you may streamline the code using std::chrono::parse.
Validate your input with a regex like this regex time.
Use Posix time to create arrival and departure objects.
Use diffTime to get the difference. Example here

Django and PostgreSQL - how to store time range?

I would like to store a time range (without dates) like "HH:MM-HH:MM".
Can you give me a hint, how can I implement it most easily? Maybe there is a way to use DateRangeField for this aim or something else.
Thanks for your spend time!
Time without date doesn't make much since if you ever need a range that span mid-night (days) You could always convert to text using to_char(<yourtimestamp>,'hh24.mi:ss') or extract the individual parts. Unfortunately Postgres does not provide an extract(time from <yourtimestamp>) function. The following function provides essentially that.
create or replace
function extract_tod(date_time_in timestamp without time zone)
returns time
language sql
as $$
select to_char(date_time_in, 'hh24:mi:ss')::time;
$$;
See here for timestatamp ranges and here for their associated functions. As for how to store then just store with the date
as a standard TIMESTAMP (date + time).

Getting current date and time in C++

I am doing a school project which basically records the in and out time of an employee(of an particular company).The employee while checking in or out should enter a unique key generated specially for him so that no one else can check in and out for him.Then referring to the employees position( A worker or a manager or something like that) his total working time each day , for a week and a month is calculated. The company starts at 8 am and ends at 5 pm for 1st shift and for second shift from 3.30 pm to 2.30 am.Plus Saturday and Sunday off.
Then after a month the program refers to the working time date stored in a file and calculates his pay(For workers its per hour salary and for managers it aint). If an employee is consistently late the details are forwarded to the HR account( so that necessary steps are taken).This will help the company log the details of their employees duty time plus give enough detail to take action if someones always late.
I'm doing this as a school project and it needn't be of enterprise class and all.. But i want the coding to perform as it should.Also i'm forced to use the old Turbo C++.
Now i'm struck in the place where the time of the employees in and out time is logged.
This coding does the work
void main( )
{
clrscr();
char dateStr [9],timeStr [9];
_strdate( dateStr);
cout<<" The current date is "<<dateStr<<'\n';
_strtime( timeStr );
cout<<" The current time is "<<timeStr<<'\n';
getch();
}
I saw it somewhere on the web but can someone help me understand how it works.
I also saw another coding
typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME;
#include <Windows.h>
#include <stdio.h>
int main()
{
SYSTEMTIME st;
GetSystemTime(&st);
printf("Year:%dnMonth:%dnDate:%dnHour:%dnMin:%dnSecond:% dn"
st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
}
I think the second one is better as it not only gives me date but also gives me the day so i can check easily for the weekends.
So help me understand how these time functions work. Also if you have any suggestions for my project they are welcome.
You need to decide the format you want to store these clock "events", both for in-memory storage and manipulation and the persistent (on-disk) storage format. When you use different formats for in-memory and on-disk (or in-database) storage, you would use methods to "marshall" or "serialize"/"de-serialize" the data (look up and read about these terms). You also want to decide whether these datetime "events" will be stored or displayed in UTC (Zulu-time, GMT), or local time. You may find that storing these 'timestamps' in UTC is the best, and then you need functions/methods/routines to convert human-readable, displayable values to/from local time to UTC time.
Consider defining a "class" that has the above methods. Your class should have a method to record the current time, convert to human readable, and serialize/de-serialize the data.
Though printf works in C++, you might want to use the stream operators you have used in your first example, as they are more in the spirit of C++. Consider defining a parse method to de-serialize the data, and a to_string method (ruby uses to_s) to serialize (though reading up on stream operator overloading, and overloading the '<<' operator is more the C++ way).
The first uses C library functions (though Microsoft extensions to the standard libc). The second uses the winapi function GetSytemTime.
Both will give the system time.
The first thing I'd look at is what the rest of your code uses. You should distinguish between what is winapi code, C code and C++ code, currently your question uses a mixture of all three.
The C++ method is preferred (if you are intending to write in C++) which would be to use the newer library. The C method is as per your first example, though without mixing libc functions with stream operators (a c++ feature). The winapi method is as per your second example (I'll forgive the use of printf as FormatMessage is a pain).

How to add a timestamp to OutputDebugString()?

I am writing a C++ application, and I want to add a timestamp to OutputDebugString(). I already know that if I watch the application using DebugView, it automatically show timestamps. But for a particular reason I want to add TimeStamps to any string I pass to OutputDebugString().
What would some sample code be?
You could use QueryPerformanceCounter and QueryPerformanceFrequency to get a high-resolution timestamp. If you set a variable to the value returned by QueryPerformanceCounter before your program really starts executing, you can achieve the same effect as debug view by subtracting this initial value from the current performance counter value when printing to a debug string. GetTickCount is another API you can use, although the resolution isn't as good.