How to convert time into an integer - c++

I have the following code:
#include <ctime>
#include <stdio.h>
#include <iostream>
#include <chrono>
using namespace std;
const std::string currentDateTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%X", &tstruct);
return buf;
}
int main() {
std::cout << "Current Time is: " << currentDateTime() << std::endl;
return 0;
}
I compile this and i get: Current Time is: 18:30:11
I want to know how to convert that into an integer so it appears as just 18.5 or something along those lines. I want to do it because I want to create a timetable.
Example: if its 10:30, I want the program to be able to tell me what subject i have (for school).
Something like this:
if(time == 10.5)
std::cout<<(subject);
Any advice on how to do this? I'm fairly new to c++ and I'm not sure if I'm going about this the completely wrong way. Is there another way to do this?
Thanks in advance.

I suppose you mean converting the time to a floating point number. In your currentDateTime function you already use struct tm. Based on that you could get a float hour value by:
time_t now = time(0);
struct tm tstruct = *localtime(&now);
float f = tstruct.tm_hour + tstruct.tm_min / 60.0 + tstruct.tm_sec / 3600.0;
cout << f << endl; // prints 10.1025 at 10:06:09

Related

c++ if the current time = given time

i need help i have a simple program but it wont work
here is my code
i want to check if the current system time equals to the given time and do something
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdio.h>
#include <time.h>
#pragma warning(disable : 4996)
const std::string currentDateTime() {
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
return buf;
}
int main() {
while (true)
{
currentDateTime();
char * currtimetochar = strcpy(new char[currentDateTime().length() + 1], currentDateTime().c_str());
//std::cout << idokes << std::endl;
if (currtimetochar == "2020-08-31.19:29:59")//given time date for example {
std::cout << "success!" << std::endl;
// do something more
}
}
getchar();
}
A better approach would be to encode a given time string to a LOCALTIME or SYSTEMTIME and compare that instead of comparing strings whose format would change in different locales. SYSTEMTIME is better for "absolute time comparisons" (it's in UTC) although using LOCALTIME may be sufficient to meet your needs.

Trying to convert postgres time stamp string to c++ time stamp

I have PostgreSQL timestamp string:
2020-07-06 09:30:00.646533
I'm trying to convert it to timeval struct, I tried using this answer, but I'm getting this output:
Thu Jan 1 00:33:40 1970
This is my code:
#include <iostream>
int main()
{
std::string ss("2020-07-06 09:30:00.646533");
auto t = atoll(ss.c_str());
time_t time = atoi(ss.c_str());
std::cout << asctime(gmtime(&time));
return 0;
}
When running with debugger, I see that this line
auto t = atoll(ss.c_str());
isn't working/set time with values.
How can i fix it?
atoll and atoi simply parse integers of various sizes from a string. They aren't great functions to use in general as they have no way of indicating that they have failed to parse the string. std::stoi and friends are the better functions to use. However in this case we don't have a number we have a date string so std::stoi won't work either (but it can at least tell you it didn't work).
c++20 comes with much better date support, until then Howard Hinnant's date library provides the same functionality:
#include "date.h"
#include <iostream>
#include <sstream>
#include <chrono>
int main()
{
std::stringstream ss("2020-07-06 09:30:00.646533");
// convert string to date time
std::chrono::system_clock::time_point time;
ss >> date::parse("%F %T", time);
if (!ss) {
std::cout << "invalid date\n";
return 1;
}
// get the amount of time since the epoch, assumes std::chrono::system_clock uses the same epoch as timeval
auto sinceEpoch = time.time_since_epoch();
// get the whole number of seconds
auto seconds = date::floor<std::chrono::seconds>(sinceEpoch);
// get the remaining microseconds
auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(sinceEpoch - seconds);
std::cout << seconds.count() << ", " << microseconds.count() << "\n";
return 0;
}
If you must re-invent the wheel you can do it using the pre c++20 standard library:
#include <iostream>
#include <sstream>
#include <chrono>
#include <iomanip>
int main()
{
std::stringstream ss("2020-07-06 09:30:00.646533");
std::tm tm;
// convert string to date time
std::chrono::system_clock::time_point time;
double fraction;
ss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S") >> fraction;
if (!ss) {
std::cout << "invalid date\n";
return 1;
}
time_t seconds = mktime(&tm);
int64_t microseconds = fraction * 1'000'000;
std::cout << seconds << ", " << microseconds << "\n";
return 0;
}
Note that the microseconds should really be parsed as an integer not a double but you have to be careful to handle strings with different numbers of digits after the decimal point and with leading zeros.
you can use like this:
#include<ctime>
#include<iotream>
int main()
{
std::string ss = "2020-07-06 09:30:00.646533";
auto i = ss.find_first_of('.');
std::string line(ss.begin()+(i+1),ss.end());
std::tm tm = {};
tm.tm_isdst = -1; // <- to set not to use day lghite saveing.
strptime(ss.c_str(), "%F %H:%M:%S", &tm); //<-enter the data to tm
start.tv_sec = mktime(&tm); //<-convert tm to time_t
start.tv_usec = stoi(line); // <- set the usec from the stirng
//IF you want the other why around
strftime(tmbuf, sizeof tmbuf, " %F %H:%M:%S", localtime(&start.tv_sec));
snprintf(buf, sizeof buf, "%s.%06ld", tmbuf, start.tv_usec);
std::cout << tmbuf;
return 0;
}
output:
2020-07-06 09:30:00.646533

How to convert a "%Y%m%d" format string into a time_t variable in C++?

I'm trying to convert strings into time_t variables. Here's the code I tried:
#include "pch.h"
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
using namespace std;
time_t String_to_timet1(string endDate) {
tm tm = { 0 };
stringstream ss(endDate);
ss >> get_time(&tm, "%Y-%m-%d %H:%M:%S");
time_t epoch = mktime(&tm);
return epoch;
}
time_t String_to_timet2(string endDate) {
tm tm = { 0 };
stringstream ss(endDate);
ss >> get_time(&tm, "%Y%m%d");
time_t epoch = mktime(&tm);
return epoch;
}
int main()
{
time_t time_certainTime1 = String_to_timet1("2019-01-01 00:00:00");
cout << time_certainTime1 << endl;
time_t time_certainTime2 = String_to_timet2("20190101");
cout << time_certainTime2 << endl;
return 0;
}
I expected that the results would be the same, but when I run the code with Visual Studio 2017, the results are:
1546268400
-1
and when I run the same code on https://www.onlinegdb.com/online_c++_compiler, the results are:
1546300800
1546300800
Question: Why does Visual Studio give me -1 when it gets a "%Y%m%d" typed string (when the online compiler gives me the result I expected)? How to make a time_t variable with such format?
In the documentation for both %m and %d it says leading zeros permitted but not required. This means that it's actually underspecified if it will work without separators or not.

How do I get the current date in C++?

I have been trying to get the current date in C++ for a while now and I cannot figure out what I am doing wrong. I have looked at several sites and all of the solutions that I implement I get an error that says, “This function or variable may be unsafe. Consider using localtime_s instead.” I tried several of the solutions found here (including the one below) but I could not get any of them to work. What am I doing wrong?
#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>
using namespace std;
int main()
{
const int SALARY = 18;
const int COMMISSION = .08;
const int BONUS = .03;
int monthlySales;
int appointmentNumber;
time_t t = time(0); // get time now
struct tm * now = localtime(&t);
string name;
//this is where the user adds their name and date
cout << "Please enter the sales representative's name: ";
cin >> name;
cout << "Please enter the number of appointments: ";
cin >> appointmentNumber;
cout << "Please enter the amount of sales for the month: $";
cin >> monthlySales;
//clear screen and execute code
system("cls");
cout << setfill(' ');
cout << "Sales Representative:" << name << endl;
cout << "Pay Date:" << (now->tm_mon + 1) << " " << now->tm_mday << " " << (now->tm_year + 1900) << endl;
cout << "Work Count:" << appointmentNumber << "Sale Amount"
<< monthlySales << endl;
system("pause");
return 0;
}
You can try below code and description beneath it.
#include <iostream>
#include <ctime>
int main ()
{
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,80,"%d-%m-%Y %I:%M:%S",timeinfo);
std::string str(buffer);
std::cout << str;
return 0;
}
Function
time_t time (time_t* timer);
function returns this value, and if the argument is not a null pointer, it also sets this value to the object pointed by timer.
Parameters
timer
Pointer to an object of type time_t, where the time value is stored.you can also pass it null pointer in case not required
Return Value
The current calendar time as a time_t object.If the function could not retrieve the calendar time, it returns a value of -1.
Here is how I do it:
#include "date/tz.h"
#include <iostream>
int
main()
{
using namespace std::chrono;
std::cout << date::make_zoned(date::current_zone(), system_clock::now()) << '\n';
}
which just output for me:
2016-10-18 10:39:10.526768 EDT
I use this C++11/14 portable, free, open-source library. It is thread-safe. It is based on <chrono>. It is type safe and easy to use. If you need more functionality, this library will do it.
Get the local time in another timezone
Convert local time directly from one timezone to another.
Take leap seconds into account in time computations.
Stream out / stream in time stamps round trip with any precision, and no loss of information.
Search all timezones for a property (such as abbreviation or offset).
This library is being proposed to the C++ standards committee, draft here.
You're getting this warning perhaps because localtime() is not thread-safe. Two instances calling this function might result in some discrepancy.
[...] localtime returns a pointer to a static buffer (std::tm*).
Another thread can call the function and the static buffer could be
overwritten before the first thread has finished reading the content
of the struct std::tm*.
The standard and cross-platform way is to use chrono.
#include <iostream>
#include <chrono>
int main(){
std::time_t now_time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << "Now:" << std::ctime(&now_time);
}
This is another way that could work:
time_t current_time;
struct tm *timeinfo;
time(&current_time);
timeinfo = localtime(&current_time);
string date = asctime(timeinfo);
I greatly appreciate all of your timely the responses. Ultimately I was able to use a variation of Heemanshu Bhalla’s response. I added ‘_CRT_SECURE_NO_WARNINGS’ to the preprocessor definitions by going here then I altered Heemanshu’s code to the following code. This suited my needs.
#include <iostream>
#include <ctime>
#include <string>
using namespace std;
int main()
{
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 80, "%m/%d/%Y ", timeinfo);
string str(buffer);
cout << str << endl;
system("PAUSE");
return 0;
}

String representation of time_t?

time_t seconds;
time(&seconds);
cout << seconds << endl;
This gives me a timestamp. How can I get that epoch date into a string?
std::string s = seconds;
does not work
Try std::stringstream.
#include <string>
#include <sstream>
std::stringstream ss;
ss << seconds;
std::string ts = ss.str();
A nice wrapper around the above technique is Boost's lexical_cast:
#include <boost/lexical_cast.hpp>
#include <string>
std::string ts = boost::lexical_cast<std::string>(seconds);
And for questions like this, I'm fond of linking The String Formatters of Manor Farm by Herb Sutter.
UPDATE:
With C++11, use to_string().
Try this if you want to have the time in a readable string:
#include <ctime>
std::time_t now = std::time(NULL);
std::tm * ptm = std::localtime(&now);
char buffer[32];
// Format: Mo, 15.06.2009 20:20:00
std::strftime(buffer, 32, "%a, %d.%m.%Y %H:%M:%S", ptm);
For further reference of strftime() check out cppreference.com
The top answer here does not work for me.
See the following examples demonstrating both the stringstream and lexical_cast answers as suggested:
#include <iostream>
#include <sstream>
int main(int argc, char** argv){
const char *time_details = "2017-01-27 06:35:12";
struct tm tm;
strptime(time_details, "%Y-%m-%d %H:%M:%S", &tm);
time_t t = mktime(&tm);
std::stringstream stream;
stream << t;
std::cout << t << "/" << stream.str() << std::endl;
}
Output: 1485498912/1485498912
Found here
#include <boost/lexical_cast.hpp>
#include <string>
int main(){
const char *time_details = "2017-01-27 06:35:12";
struct tm tm;
strptime(time_details, "%Y-%m-%d %H:%M:%S", &tm);
time_t t = mktime(&tm);
std::string ts = boost::lexical_cast<std::string>(t);
std::cout << t << "/" << ts << std::endl;
return 0;
}
Output: 1485498912/1485498912
Found: here
The 2nd highest rated solution works locally:
#include <iostream>
#include <string>
#include <ctime>
int main(){
const char *time_details = "2017-01-27 06:35:12";
struct tm tm;
strptime(time_details, "%Y-%m-%d %H:%M:%S", &tm);
time_t t = mktime(&tm);
std::tm * ptm = std::localtime(&t);
char buffer[32];
std::strftime(buffer, 32, "%Y-%m-%d %H:%M:%S", ptm);
std::cout << t << "/" << buffer;
}
Output: 1485498912/2017-01-27 06:35:12
Found: here
Standard C++ does not have any time/date functions of its own - you need to use the C localtime and related functions.
the function "ctime()" will convert a time to a string.
If you want to control the way its printed, use "strftime". However, strftime() takes an argument of "struct tm". Use "localtime()" to convert the time_t 32 bit integer to a struct tm.
The C++ way is to use stringstream.
The C way is to use snprintf() to format the number:
char buf[16];
snprintf(buf, 16, "%lu", time(NULL));
Here's my formatter -- comments welcome. This q seemed like it had the most help getting me to my a so posting for anyone else who may be looking for the same.
#include <iostream>
#include "Parser.h"
#include <string>
#include <memory>
#include <ctime>
#include <chrono>
#include <iomanip>
#include <thread>
using namespace std;
string to_yyyyMMddHHmmssffffff();
string to_yyyyMMddHHmmssffffff() {
using namespace std::chrono;
high_resolution_clock::time_point pointInTime = high_resolution_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(pointInTime);
microseconds micros = duration_cast<microseconds>(pointInTime.time_since_epoch());
std::size_t fractional_microseconds = micros.count() % 1'000'000;
std:stringstream microstream;
microstream << "00000" << fractional_microseconds;
string formatted = microstream.str();
int index = formatted.length() - 6;
formatted = formatted.substr(index);
std::stringstream dateStream;
dateStream << std::put_time(std::localtime(&now_c), "%F %T") << "." << formatted;
formatted = dateStream.str();
return formatted;
}
There are a myriad of ways in which you might want to format time (depending on the time zone, how you want to display it, etc.), so you can't simply implicitly convert a time_t to a string.
The C way is to use ctime or to use strftime plus either localtime or gmtime.
If you want a more C++-like way of performing the conversion, you can investigate the Boost.DateTime library.
localtime did not work for me. I used localtime_s:
struct tm buf;
char dateString[26];
time_t time = time(nullptr);
localtime_s(&buf, &time);
asctime_s(dateString, 26, &buf);