'Extract the century of a date from a string
My task is to output the current century of a given date. The date can be represented as a string
; for example, 19.03.2022
.
How can I retrieve the year and century of such strings?
Solution 1:[1]
string date = "19.03.2022";
int century = (date[6] - '0') * 10 + (date[7] - '0');
if(date[8] != '0' || date[9] != '0') century++;
cout<<century<<endl;
Output: 21
Complexity: O(1)
Solution 2:[2]
The year of the given string
is always contained within the last four characters, so you can use string::substr
and then std::stoi
to retrieve the year:
string str = "19.03.2022";
int year = stoi(str.substr(6, 4)); // year = "2022"
After that, you can use year
to calculate the century:
int century = year/100 + 1; // century = 21
Solution 3:[3]
# we can also get the same for a list of dates, extract the first 2 index values
# from the year string and convert it to integer and the back to string
# if the year ends like '07' in the first string else just leave it as it is if
# it ends with '00'
# finally we can simply add 1 if the year ends with '07' in the first string,
# and we have what we want
date_list = ['1907-08-15','1883-06-27','1900-01-01','1901-01-01','2005-09-01',
'1775-11-23','1800-01-01']
cur_century = list(map(lambda x: x[0:2] if x[2:4]=='00' else str(int(x[0:2])+1)
,date_list))
print(cur_century )
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Daniel |
Solution 2 | |
Solution 3 | Manendar |