Convert string to time_t

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pbrama
    New Member
    • Oct 2007
    • 1

    Convert string to time_t

    I have a customer that supplied me with a text file that has some data and dates stored, apparently, as milliseconds since 01/01/1970 12:00a. I need to display the date/time in their application. I believe I can use the localtime routine but that requires the data passed to it to be in time_t format. I currently have it as a string.

    One sample number stored in a string 1192034967000. How do I convert this to time_t so I can get the date/time conversion or is there a better way?

    Thanks
  • Cucumber
    New Member
    • Sep 2007
    • 90

    #2
    The function sscanf does that, it let you assign variable values from a string.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      time_t is just an unsigned int. You can convert from a string to time_t using a stringstream.
      [code=cpp]
      string str = "1192034967000" ;
      time_t t;
      stringstream ss;
      ss << str;
      ss >> t;
      [/code]

      Be aware that time_t in its 32-but form is no good after Jan 18,2038.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Originally posted by weaknessforcats
        [code=cpp]
        string str = "1192034967000" ;
        time_t t;
        stringstream ss;
        ss << str;
        ss >> t;
        [/code]
        This wont work. You have forgotten that time_t is the time in seconds since 01/01/1970 12:00a but the number is the time in milliseconds. Worst if time_t is 32 bit because 1192034967000 takes more than 32 bits to represent it.

        You need to drop the last 3 digits first and convert 1192034967 to a time_t.

        Comment

        Working...