2017-10-19 1 views
1

구문 분석 할 문자열을 웹 서버에서받는 것으로 가정합니다. 이 문자열은 YYYY-MM-DD 형식의 날짜를 포함합니다. 내가 원하는 것은 그 날의 시작을 나타내는 타임 스탬프로 변환하는 것이므로 초, 분 및 시간을 원하지 않습니다.타임 스탬프에서 시간, 분 및 초를 제거하는 데 사용되는 구문 문자열

예를 들어, 한 번 YYYY-MM-DD 형식으로 변환 된 현재 날짜의 타임 스탬프를 추출하려고합니다. 여기 코드는 다음과 같습니다

#include <chrono>                                                                
#include <iomanip>                                                                
#include <iostream>                                                                
#include <sstream> 
int main() 
{ 
    // Current time at GMT 
    std::time_t now = std::time(0); 
    std::tm *now_tm = std::gmtime(&now); 
    std::ostringstream oss; 
    // Extract yyyy-mm-dd = %F 
    oss << std::put_time(now_tm, "%F"); 
    // Use oss to get a date without seconds from 
    // current time at gmt 
    std::tm tm; 
    std::istringstream ss(oss.str()); 
    ss >> std::get_time(&tm, "%F"); 
    std::time_t current_date = std::mktime(&tm); 
    std::cout << oss.str() << std::endl; 
    std::cout << "cd: " << current_date << std::endl; 
    return 0; 
} 

출력은 다음과 같습니다

2017-10-19 
cd: 1908337984324104 

추출 된 타임 스탬프는 분명 잘못된 것입니다. 구문 분석에서 문제가있는 곳은 %F 형식을 사용하는 2017-10-19 문자열입니까?

답변

1

documentation of std::get_time에는 변환 지정자가 % F 없습니다. 스트림 플래그 (항상해야하는!)를 검사 할 때, 적어도 컴파일러에서는 변환이 실패했음을 알립니다.

그래서 % Y- % m- % d로 바꾸면 변환이 성공합니다. 마지막으로, tm 변수를 초기화하지 않고 (예 : 값 초기화에 의해) tm 변수를 기본 설정했습니다. 뿐만 아니라이 고정되면, 코드는 예상대로 작동합니다

#include <chrono>                                                                
#include <iomanip>                                                                
#include <iostream>                                                                
#include <sstream> 
int main() 
{ 
    // Current time at GMT 
    std::time_t now = std::time(0); 
    std::tm *now_tm = std::gmtime(&now); 
    std::ostringstream oss; 
    // Extract yyyy-mm-dd = %F 
    oss << std::put_time(now_tm, "%Y-%m-%d"); 
    // Use oss to get a date without seconds from 
    // current time at gmt 
    std::tm tm{ }; // value-initialize! 
    std::istringstream ss(oss.str()); 
    ss >> std::get_time(&tm, "%Y-%m-%d"); 
    if(!ss) std::cout << "conversion error\n"; 
    else { 
     std::time_t current_date = std::mktime(&tm); 
     std::cout << current_date << '\n'; 
     std::cout << "cd: " << current_date << '\n'; 
    } 
    return 0; 
} 

http://coliru.stacked-crooked.com/a/d86aa1e1d890a14d

+0

대단히 고마워요! 다른 시간 지정 함수의 문서를보고 있었는데, 그것이 같을 것이라고 추측합니다. 내가 틀렸어. – nessuno

1

당신은 Howard Hinnant's, free, open-source, header-only chrono-extension library를 사용하여 chrono 타입 시스템의 안전을 떠나지 않고이 작업을 수행 할 수 있습니다.

#include "date/date.h" 
#include <iostream> 

int 
main() 
{ 
    std::istringstream ss{"2017-10-19"}; 
    date::sys_seconds tp; 
    ss >> date::parse("%F", tp); 
    std::cout << date::format("%F\n", tp); 
    using date::operator<<; 
    std::cout << "cd: " << tp.time_since_epoch() << '\n'; 
} 

date::sys_secondsUnix Time에서 chrono::seconds 세는 std::chrono::time_point이다. %F을 사용하여 직접 구문 분석 할 수 있습니다. 동일한 형식 문자열 (%F)을 사용하여 형식을 지정하고 기본 카운트 인 chrono::seconds을 검사 할 수도 있습니다. 이 프로그램 출력 :

2017-10-19 
cd: 1508371200s 
+0

좋습니다. 귀하의 제안에 감사드립니다. 내 upvote 유지 – nessuno

관련 문제