Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the current time as a YYYY-MM-DD-HH-MM-SS string

Tags:

I'm trying to get the current time as a "YYYY-MM-DD-HH-MM-SS" formatted string in an elegant way. I can take the current time in ISO format from Boost's "Date Time" library, but it has other delimiting strings which won't work for me (I'm using this in a filename). Of course I can just replace the delimiting strings, but have a feeling that there's a nicer way to do this with date-time's formatting options. Is there such a way, and if so, how can I use it?

like image 412
ltjax Avatar asked Mar 25 '11 21:03

ltjax


People also ask

How do I print the Date on HH MM SS?

You can use as: Date dt = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String check = dateFormat. format(dt); System. out.

How do I format a string to mm dd yyyy?

string dateString = int. Parse("20120321"). ToString("yyyy/MM/dd");

What is SSSZ in Date format?

Dates are formatted using the following format: "yyyy-MM-dd'T'hh:mm:ss'Z'" if in UTC or "yyyy-MM-dd'T'hh:mm:ss[+|-]hh:mm" otherwise. On the contrary to the time zone, by default the number of milliseconds is not displayed. However, when displayed, the format is: "yyyy-MM-dd'T'hh:mm:ss.


2 Answers

Use std::strftime, it is standard C++.

#include <cstdio> #include <ctime>  int main () {     std::time_t rawtime;     std::tm* timeinfo;     char buffer [80];      std::time(&rawtime);     timeinfo = std::localtime(&rawtime);      std::strftime(buffer,80,"%Y-%m-%d-%H-%M-%S",timeinfo);     std::puts(buffer);      return 0; } 
like image 128
Null Set Avatar answered Oct 26 '22 10:10

Null Set


The answer depends on what you mean by get and take. If you are trying to output a formatted time string, use strftime(). If you are trying to parse a text string into a binary format, use strptime().

like image 45
jbruni Avatar answered Oct 26 '22 09:10

jbruni