Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

How to get the month name from a date in C++

1 Answer

0 votes
#include <iostream>
#include <iomanip>
#include <sstream>
#include <ctime>

std::string getMonthName(const std::string& dateString, const std::string& format) {
    std::istringstream ss(dateString);
    std::tm t{};
    ss >> std::get_time(&t, format.c_str());

    if (ss.fail()) {
        return "Invalid date format"; 
    }

    char monthName[32]; 
    std::strftime(monthName, sizeof(monthName), "%B", &t); // %B for full month name

    return std::string(monthName);
}

int main() {
    std::string date = "2023-03-17";
    std::string format = "%Y-%m-%d";
    std::string month = getMonthName(date, format);
    std::cout << date << " -> " << month << std::endl; 

    date = "12/27/2024";
    format = "%m/%d/%Y";
    month = getMonthName(date, format);
    std::cout << date << " -> " << month << std::endl; 

    date = "Jan 7, 2025";
    format = "%b %d, %Y"; // %b for abbreviated month name
    month = getMonthName(date, format);
    std::cout << date << " -> " << month << std::endl; 

    std::string invalidDate = "2021/13/19"; // Invalid month - 13
    std::string invalidFormat = "%Y-%m-%d";
    std::string resultInvalid = getMonthName(invalidDate, invalidFormat);
    std::cout << invalidDate << " -> " << resultInvalid << std::endl; 
}

  
  
/*
run:

2023-03-17 -> March
12/27/2024 -> December
Jan 7, 2025 -> January
2021/13/19 -> Invalid date format
   
*/

 



answered Jan 7, 2025 by avibootz

Related questions

1 answer 92 views
1 answer 95 views
1 answer 106 views
1 answer 86 views
1 answer 85 views
2 answers 76 views
...