How to deal with time in C++? - 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

Related

C++ Setting the Date for localtime

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.

Graphlab Date Manipulaiton

I have a dataset that I am trying to manipulate in GraphLab. I want to convert a UNIX Epoch timestamp from the input file (converted to an SFrame) into a human readable format so I can do analysis based on hour of day and day of week.
time_array is the column/feature of the SFrame sf representing the timestamp, I have broken out just the EPOCH time to simplify things. I know how to convert the time of one row, but I want a vector operation. Here is what I have for one row.
time_array = sf['timestamp']
datetime.datetime.fromtimestamp(time_array[0]).strftime('%Y-%m-%d %H')
You can also get parts of the time from the timestamp to create another column, by which to filter (e.g., get the hour):
sf['hour'] = [x.strftime('%H')for x in sf['timestamp']]
So after staring at this for awhile and then posting the question it came to me, hopefully someone else can benefit as well. Use the .apply method with the datetime.datetime() function
sf['date_string'] = sf['timestamp'].apply(lambda x: datetime.datetime.fromtimestamp(x).strftime('%Y-%m-%d %H'))
you can also use the split_datetime API to split the timestamp to multiple columns:
split_datetime('timestamp',limit=['hour','minute'])

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).

Multiple User Input Choices C++

I am in a beginning C++ class, and right now we are going over functions. For an assignment I have to write two functions. One should take three int arguments representing a time (hours, minutes, seconds), and return the equivalent time in seconds. The second function should take one int argument (seconds) and return the equivalent time in hours, minutes, seconds format.
I'm wondering if there is a way to give the user a choice on how many arguments to enter. For example, is there a way that I can prompt something like "Enter a time in seconds or hours, minutes, seconds form: " and if the user enters only one input call one function, but if they enter three call the other?
I realize I could give the user a choice first, such as "Enter '1' to convert from seconds to hours, minutes, seconds. Enter '2' to convert from hours, minutes, seconds to seconds." and then run a separate cin statement depending on what they choose, but is there a way to do it without this additional typing from the user?
Yes, you can do this fairly easily. Prompt the user for input. Use std::getline to read their entire input as a string. Check whether that string contains only digits (so it's one input) or has something like spaces or commas (indicating it's more than one input).
Convert the appropriate number of inputs, and call the chosen function.
There is. The simple way is to try to parse the string in two different formats. If one fails, try the other. The format that succeeded indicates which function you should call.
If you give examples of acceptable input for each function, perhaps I could offer a concrete example.

Custom Format for Current Date and Time in C++

I am trying to save a file into a directory of files based on the current date and time. I am trying to get the format of the following:
"FullMonth-FullYear" example:
"April-2011"
"FullMonth-littleDay-year" example:
"March-7-11"
hour-minutes-seconds. example: "18:05:09" in 24 hour format
It depends on the format you have the time in right now. I'm a big fan of sprintf(), and since I mostly deal with big piles of seconds, milliseconds, or nanoseconds, I do a lot of modulus arithmetic to get what I want.
boost.date_time can do arbitrary formatting, to a higher a degree of precision than the standard functions are typically capable of. Specifically, see Date Time Input/Output Format Flags.