-2

I have a string containing the seconds from the epoch, how do i convert this string to a format
as such -

YEAR-MONTH-DAY HH:MM:SS

Here MONTH should display the month number and DAY gives the day number. Also the time needs to be in 24 hour format.
For example :

2019-06-26 11:14:25

I have tried using strptime but havent been successful in doing so, could someone help me in what I am doing wrong.
This is what i have tried so far

int main()
{
    string timee = "12341234534";

    const char *ptr = timee.c_str();
    struct tm tim;
    strptime(ptr, "%S", &tim);
    time_t abcd = mktime(&tim);

    cout<<abcd;
    return 0;

}

Found this code snippet on another stackoverflow link How to convert a string variable containing time to time_t type in c++?

  • 1
    Tell us what exactly have you tried (your code) – YesThatIsMyName Jun 26 '19 at 05:50
  • 2
    @YesThatIsMyName.. I have added the code please check. Thank You! – Karan Motiramani Jun 26 '19 at 05:54
  • 2
    A [`strptime` manual or reference](http://man7.org/linux/man-pages/man3/strptime.3.html) should be very useful. Don't *guess* when programming, it will seldom work well. – Some programmer dude Jun 26 '19 at 05:56
  • 2
    Also note that the "input" operator `>>` stops on *space*. You can't use it to read lines containing spaces. – Some programmer dude Jun 26 '19 at 05:58
  • @Someprogrammerdude, I'll check the manual and try, Thank You! – Karan Motiramani Jun 26 '19 at 05:58
  • @Someprogrammerdude, i dont need lines, just a string containing the seconds from epoch (eg - 12341234534) is enough – Karan Motiramani Jun 26 '19 at 05:59
  • 1
    Lastly, `strptime` is not a standard C or C++ function. You might want to read about [`std::get_time`](https://en.cppreference.com/w/cpp/io/manip/get_time) to read and parse the input. – Some programmer dude Jun 26 '19 at 06:00
  • For future questions please read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). What that should tell you is to (among other things) include the input to your program (unless it could be hard-coded which is even better) and also the expected and actual output of the [mcve]. – Some programmer dude Jun 26 '19 at 06:09

1 Answers1

1

Your question is a little confusing, but I think I figured out what you want...

If the time is in a time_t compatible format, then just read it directly into a time_t variable, and convert it through std::localtime so you can output it in the wanted format using std::put_time.

Something like

std::time_t time;
std::cin >> time;
std::cout << std::put_time(std::localtime(&time), "%F %T") << '\n';
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621