Convert a date in a string to FILETIME - c++

I have an imput .txt file, which contains a date. The date is in the form DDMONYY, as in 08JUN98 or 16NOV05. I need to compare this date to the creation date of the file, and see which is sooner.
FILETIME seems like the appropriate form, especially since there is a CompareFileTime function. However, I have a problem converting the date into file time.
I can extract the date from the file and convert it into numbers (days 1-31, month 1-12, year 1900-20whatever) so I don't need help with that, but feel free to comment on it anyway.
The real problem is that I can't figure out how to get these values into a FILETIME format. Right now I have them as three different strings(or int's if that helps more) one for day, month and year. If you could help me make the jump from string to FILETIME that would be great.
Or, if there is a completely better way that I missed during my research, please feel free to suggest it.
If you want, I can post what I have, but I don't think it'll help since it's only getting to the string/int's.
if it makes it any clearer, the values I have in my variables at this point, for May 3rd, 2002, would be something along the lines of
string day = "03";
string month ="5";
string year = "2002;
int dayint = 3;
int monthint = 5;
int yearint = 2002;
And I need a way to convert this to a FILETIME
Thanks a bunch.
EDIT:
I'm not sure how I would fill a SYSTEMTIME structure, or even how to do it for a different time system. So I guess that is more my question.
I should have also mentioned that I only need accuracy of days. Hours and anything smaller aren't really of concern to me.
EDIT2:
I must not have tried giving the SYSTEMTIME int values, because that seems to work. However, I am running into issues when I try to convert that systemtime to a filetime. It states "Error: no suitable converstion from "SYSTEMTIME" to "const SYSTEMTIME *" exists". I'm not sure how to fix this, since if I define the systime variable as const SYSTEMTIME I can't assign values to it.
here's the relevant code, if it helps
SYSTEMTIME systime;
LPFILETIME ftime1;
LPFILETIME ftime2;
int dayint=6;
int monthint=12;
int yearint=1989;
systime.wDay = dayint;
systime.wMonth = monthint;
//and so on for year, hour, etc.
SystemTimeToFileTime(systime,ftime1); //This is where the aforementioned error occurs
GetFileTime(filename, NULL, NULL, ftime2); //I'm also not sure about this line... feel free to critique it. I'm only interested in the last written time so I put NULL for the other times... When I check the values for this (in SYSTEMTIME) it only returns 52428, so I don't think this line is working correctly...
CompareFileTime(ftime1,ftime2);
Of course, the values for day, month, year aren't hardcoded in the actual code.
EDIT3:
I have a bad handle....
I'm going to try to fix that....
Thanks for your help Ben Voigt
If I can't get it, I guess I'll be back

You can fill in a SYSTEMTIME structure and then call SystemTimeToFileTime
You may want to use LocalFileTimeToFileTime afterwards, depending on whether you want to specify the hours in UTC or local time.

Related

Getting current date and time in C++

I am doing a school project which basically records the in and out time of an employee(of an particular company).The employee while checking in or out should enter a unique key generated specially for him so that no one else can check in and out for him.Then referring to the employees position( A worker or a manager or something like that) his total working time each day , for a week and a month is calculated. The company starts at 8 am and ends at 5 pm for 1st shift and for second shift from 3.30 pm to 2.30 am.Plus Saturday and Sunday off.
Then after a month the program refers to the working time date stored in a file and calculates his pay(For workers its per hour salary and for managers it aint). If an employee is consistently late the details are forwarded to the HR account( so that necessary steps are taken).This will help the company log the details of their employees duty time plus give enough detail to take action if someones always late.
I'm doing this as a school project and it needn't be of enterprise class and all.. But i want the coding to perform as it should.Also i'm forced to use the old Turbo C++.
Now i'm struck in the place where the time of the employees in and out time is logged.
This coding does the work
void main( )
{
clrscr();
char dateStr [9],timeStr [9];
_strdate( dateStr);
cout<<" The current date is "<<dateStr<<'\n';
_strtime( timeStr );
cout<<" The current time is "<<timeStr<<'\n';
getch();
}
I saw it somewhere on the web but can someone help me understand how it works.
I also saw another coding
typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME;
#include <Windows.h>
#include <stdio.h>
int main()
{
SYSTEMTIME st;
GetSystemTime(&st);
printf("Year:%dnMonth:%dnDate:%dnHour:%dnMin:%dnSecond:% dn"
st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
}
I think the second one is better as it not only gives me date but also gives me the day so i can check easily for the weekends.
So help me understand how these time functions work. Also if you have any suggestions for my project they are welcome.
You need to decide the format you want to store these clock "events", both for in-memory storage and manipulation and the persistent (on-disk) storage format. When you use different formats for in-memory and on-disk (or in-database) storage, you would use methods to "marshall" or "serialize"/"de-serialize" the data (look up and read about these terms). You also want to decide whether these datetime "events" will be stored or displayed in UTC (Zulu-time, GMT), or local time. You may find that storing these 'timestamps' in UTC is the best, and then you need functions/methods/routines to convert human-readable, displayable values to/from local time to UTC time.
Consider defining a "class" that has the above methods. Your class should have a method to record the current time, convert to human readable, and serialize/de-serialize the data.
Though printf works in C++, you might want to use the stream operators you have used in your first example, as they are more in the spirit of C++. Consider defining a parse method to de-serialize the data, and a to_string method (ruby uses to_s) to serialize (though reading up on stream operator overloading, and overloading the '<<' operator is more the C++ way).
The first uses C library functions (though Microsoft extensions to the standard libc). The second uses the winapi function GetSytemTime.
Both will give the system time.
The first thing I'd look at is what the rest of your code uses. You should distinguish between what is winapi code, C code and C++ code, currently your question uses a mixture of all three.
The C++ method is preferred (if you are intending to write in C++) which would be to use the newer library. The C method is as per your first example, though without mixing libc functions with stream operators (a c++ feature). The winapi method is as per your second example (I'll forgive the use of printf as FormatMessage is a pain).

unable to get fraction of seconds using strptime()

I am receiving a datetime in YYYY-MM-DDThh:mm:ss[.S+][Z|+-hh:mm] this format. and i m trying to copy that value using strptime as shown below
struct tm time = {0};
char *pEnd = strptime(datetime, "%Y-%m-%dT%H:%M:%S%Z", &time);
But I can't copy the fraction of seconds as strptime doesn't support it in C++.
So what should i do?
I found a solution using gettimeofday(). but I am already getting date and time in 'datetime' so please help me to find soluntion for it...I can use poco also . but even their we take local time.
You can remove the "S" component from the string before parsing with strptime, then use it however you like later (it won't fit anywhere in a Standard struct tm - there's no sub-second fields). Just datetime.find('.') and go from there, or use a regexp if you prefer - both tedious but not rocket science.
In C++11 you can use the the high precision timing objects in <chrono>, see the answers to this question.

Library to discover dates from text?

I need to pull a date out of a string. Since not everyone uses the official ISO format when printing their dates, it is impractical to write a date parser for every possible date format that could be used, and I need to handle as many date formats as possible - I don't control the data and can't expect it to come in a specific format.
This seems like a problem that has probably already been solved ages ago, but my Google-fu is too weak to find the solution. :(
Does there already exist a C++ library that, given a string, will return the month, day, year, hour, minute, second, etc that is referenced in that string, if any?
Pseudocode:
string s1 = "There is an expected meteor shower this Thursday,"
"August 15th 2013 at 4:39 AM.";
string s2 = "20130815T04:39:00";
date d1 = magicConverter(s1);
date d2 = magicConverter(s2);
assert(d1 == d2);
You might use the code from here, but you need to configure a mask, that tells the code which time format is used. If you write a class routine, that takes a mask and a string and gets you out the time and is able to print in any format you like, you should be well prepared. You have to look in more detail, if it also supports Daynames and Monthnames. I got it to work in python with a module providing a function that seems pretty much the same.
For more detail:
Please look at the example 2013-08-03 again. Nobody and as follows no computer is able to tell you if this date belongs to August or April, except of having a mask telling JJJJ-MM-DD or JJJJ-DD-MM. Also this library may tell you only standard masked times. So it might lead you to August in this case. But as you said it can be any date declaration, thus it does not need to follow standards, thus it can also mean March. An other possibility is to tell you about the date from the context (e.g. a table with a column of all te same time formats by looking for the increase (which would also fail if you just look at one day per month for just one year).
Another example... if I ask you 2013-05-04... to which month does it belong? You might tell me... April. I would reply "no, to the 4th of May" and vice versa for May and 5th of April. If you tell me how to solve this puzzle with two possible solutions I would understand your downvote... please think before downvoting someone trying to help you.

Oracle OCCI stmt.setTimestamp insert TIMESTAMP(6): microseconds always 0

UPDATE: The "fraction of a second" parameter to Timestamp's constructor actually takes nanoseconds... I guessed it was hundredths of a second and my low values were rounded away. Question left for reference....
I'm struggling with Oracle's C++ library - OCCI. Summarily:
creating Timestamp objects and verifying they're good to hundredths of a second (though I'd like more!)
using stmt.setTimestamp then executeUpdate() to insert into a TIMESTAMP(6) column which should preserve microseconds
selecting the row in Oracle SQL Developer: the sub-second component is always 0-ed e.g. 14-JUL-11 06.03.27.000000000.
Problem
I need subsecond precision - hopefully microseconds! We've put a lot of work into capturing that precision in our servers and need (at least some of) it for analysis.
Details
I create a Timestamp from year/month/day hour/minute/second/millisecond, reducing the last to hundredths of a second as that seems to be what the constructor supports. (No Oracle documentation I can find specifies the interpretation, but in a fromText example "xff" clearly corresponds to a ".##" hundredths suffix in the value to convert. What's the point of TIMESTAMP(6) supporting 6 decimal places if you can't insert them?)
oracle::occi::Timestamp temp =
oracle::occi::Timestamp(_env, year, month, day,
hour, minute, second, millisecond / 10);
// re-extract the broken-down time from temp to prove it's stored successfully
int ye;
unsigned mo, da, ho, mi, se, fs;
temp.getDate(ye, mo, da);
temp.getTime(ho, mi, se, fs);
return temp;
Here, fs gets the milliseconds/10 value as expected.
I use this as in:
oracle::occi::Timestamp ts;
ts = _pImpl->makeOracleTimestamp(p->ATETimeStamp);
stmt.setTimestamp(11, ts);
Where field 11 is a TIMESTAMP(6).
Selecting the row in Oracle SQL Developer, the other parts of the timestamp column are correct but the sub-second component is 0-ed ala 14-JUL-11 06.03.27.000000000.
Any insight much appreciated!
(If relevant, using MSVC++ 2005, Oracle 10.2.0.4 sdk, SQL Developer 3.0.04 - please ask if something else might be relevant).
Thanks,
Tony
Turns out the "fractional seconds" field is nominally in nanoseconds rather than hundredths. I wish Oracle would say that in their documents! I say nominally because if it really preserved the least-significant digits then the hundredths values I had would have appeared as a number of nanoseconds and I might have immediately guessed at the problem - instead it seems values < 100 nanoseconds are lost anyway (and perhaps bigger - I haven't probed the cut-off point).
Thanks to anyone who had a look at the question or tried some research / investigation.

create variable to hold time created

Im creating a contact list program and need to beable to record when the contact was created and list the contacts according to their creation date.
what can i use to give a variable a date? i know the time.h file has something inside, but i dont know how to use it with less code as possible.
perhaps
time.h seconds = timeStamp;
?
if this is the way, then what would the output be? and whats the best way to output it in order? this variable will be part of a class.
I know you can use time_t for dates. If you need higher precision, use clock_t
You can get the current time as follows. Note that what is stored is an integer value of the number of seconds since January 1st, 1970.
#include <time.h>
....
time_t s = time(NULL);
See this for further details. Hope that helps!
#include <time.h>
...
time_t seconds = time(NULL);
The seconds variable will contain the number of seconds since 1970, which is enough information to store both date and time.
You can use the asctime function to convert this value into a human-readable string.