Merge pull request #3913 from FernetMenta/aefixes
[vuplus_xbmc] / xbmc / XBDateTime.cpp
1 /*
2  *      Copyright (C) 2005-2013 Team XBMC
3  *      http://xbmc.org
4  *
5  *  This Program is free software; you can redistribute it and/or modify
6  *  it under the terms of the GNU General Public License as published by
7  *  the Free Software Foundation; either version 2, or (at your option)
8  *  any later version.
9  *
10  *  This Program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  *  GNU General Public License for more details.
14  *
15  *  You should have received a copy of the GNU General Public License
16  *  along with XBMC; see the file COPYING.  If not, see
17  *  <http://www.gnu.org/licenses/>.
18  *
19  */
20
21 #include "XBDateTime.h"
22 #include "LangInfo.h"
23 #include "guilib/LocalizeStrings.h"
24 #include "utils/log.h"
25 #include "utils/StringUtils.h"
26 #ifdef TARGET_POSIX
27 #include "XTimeUtils.h"
28 #include "XFileUtils.h"
29 #else
30 #include <Windows.h>
31 #endif
32
33 #define SECONDS_PER_DAY 86400UL
34 #define SECONDS_PER_HOUR 3600UL
35 #define SECONDS_PER_MINUTE 60UL
36 #define SECONDS_TO_FILETIME 10000000UL
37
38 static const char *DAY_NAMES[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
39 static const char *MONTH_NAMES[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
40
41 /////////////////////////////////////////////////
42 //
43 // CDateTimeSpan
44 //
45
46 CDateTimeSpan::CDateTimeSpan()
47 {
48   m_timeSpan.dwHighDateTime=0;
49   m_timeSpan.dwLowDateTime=0;
50 }
51
52 CDateTimeSpan::CDateTimeSpan(const CDateTimeSpan& span)
53 {
54   m_timeSpan.dwHighDateTime=span.m_timeSpan.dwHighDateTime;
55   m_timeSpan.dwLowDateTime=span.m_timeSpan.dwLowDateTime;
56 }
57
58 CDateTimeSpan::CDateTimeSpan(int day, int hour, int minute, int second)
59 {
60   SetDateTimeSpan(day, hour, minute, second);
61 }
62
63 bool CDateTimeSpan::operator >(const CDateTimeSpan& right) const
64 {
65   return CompareFileTime(&m_timeSpan, &right.m_timeSpan)>0;
66 }
67
68 bool CDateTimeSpan::operator >=(const CDateTimeSpan& right) const
69 {
70   return operator >(right) || operator ==(right);
71 }
72
73 bool CDateTimeSpan::operator <(const CDateTimeSpan& right) const
74 {
75   return CompareFileTime(&m_timeSpan, &right.m_timeSpan)<0;
76 }
77
78 bool CDateTimeSpan::operator <=(const CDateTimeSpan& right) const
79 {
80   return operator <(right) || operator ==(right);
81 }
82
83 bool CDateTimeSpan::operator ==(const CDateTimeSpan& right) const
84 {
85   return CompareFileTime(&m_timeSpan, &right.m_timeSpan)==0;
86 }
87
88 bool CDateTimeSpan::operator !=(const CDateTimeSpan& right) const
89 {
90   return !operator ==(right);
91 }
92
93 CDateTimeSpan CDateTimeSpan::operator +(const CDateTimeSpan& right) const
94 {
95   CDateTimeSpan left(*this);
96
97   ULARGE_INTEGER timeLeft;
98   left.ToULargeInt(timeLeft);
99
100   ULARGE_INTEGER timeRight;
101   right.ToULargeInt(timeRight);
102
103   timeLeft.QuadPart+=timeRight.QuadPart;
104
105   left.FromULargeInt(timeLeft);
106
107   return left;
108 }
109
110 CDateTimeSpan CDateTimeSpan::operator -(const CDateTimeSpan& right) const
111 {
112   CDateTimeSpan left(*this);
113
114   ULARGE_INTEGER timeLeft;
115   left.ToULargeInt(timeLeft);
116
117   ULARGE_INTEGER timeRight;
118   right.ToULargeInt(timeRight);
119
120   timeLeft.QuadPart-=timeRight.QuadPart;
121
122   left.FromULargeInt(timeLeft);
123
124   return left;
125 }
126
127 const CDateTimeSpan& CDateTimeSpan::operator +=(const CDateTimeSpan& right)
128 {
129   ULARGE_INTEGER timeThis;
130   ToULargeInt(timeThis);
131
132   ULARGE_INTEGER timeRight;
133   right.ToULargeInt(timeRight);
134
135   timeThis.QuadPart+=timeRight.QuadPart;
136
137   FromULargeInt(timeThis);
138
139   return *this;
140 }
141
142 const CDateTimeSpan& CDateTimeSpan::operator -=(const CDateTimeSpan& right)
143 {
144   ULARGE_INTEGER timeThis;
145   ToULargeInt(timeThis);
146
147   ULARGE_INTEGER timeRight;
148   right.ToULargeInt(timeRight);
149
150   timeThis.QuadPart-=timeRight.QuadPart;
151
152   FromULargeInt(timeThis);
153
154   return *this;
155 }
156
157 void CDateTimeSpan::ToULargeInt(ULARGE_INTEGER& time) const
158 {
159   time.u.HighPart=m_timeSpan.dwHighDateTime;
160   time.u.LowPart=m_timeSpan.dwLowDateTime;
161 }
162
163 void CDateTimeSpan::FromULargeInt(const ULARGE_INTEGER& time)
164 {
165   m_timeSpan.dwHighDateTime=time.u.HighPart;
166   m_timeSpan.dwLowDateTime=time.u.LowPart;
167 }
168
169 void CDateTimeSpan::SetDateTimeSpan(int day, int hour, int minute, int second)
170 {
171   ULARGE_INTEGER time;
172   ToULargeInt(time);
173
174   time.QuadPart=(LONGLONG)day*SECONDS_PER_DAY*SECONDS_TO_FILETIME;
175   time.QuadPart+=(LONGLONG)hour*SECONDS_PER_HOUR*SECONDS_TO_FILETIME;
176   time.QuadPart+=(LONGLONG)minute*SECONDS_PER_MINUTE*SECONDS_TO_FILETIME;
177   time.QuadPart+=(LONGLONG)second*SECONDS_TO_FILETIME;
178
179   FromULargeInt(time);
180 }
181
182 void CDateTimeSpan::SetFromTimeString(const CStdString& time) // hh:mm
183 {
184   if (time.size() >= 5 && time[2] == ':')
185   {
186     int hour    = atoi(time.substr(0, 2).c_str());
187     int minutes = atoi(time.substr(3, 2).c_str());
188     SetDateTimeSpan(0,hour,minutes,0);
189   }
190 }
191
192 int CDateTimeSpan::GetDays() const
193 {
194   ULARGE_INTEGER time;
195   ToULargeInt(time);
196
197   return (int)(time.QuadPart/SECONDS_TO_FILETIME)/SECONDS_PER_DAY;
198 }
199
200 int CDateTimeSpan::GetHours() const
201 {
202   ULARGE_INTEGER time;
203   ToULargeInt(time);
204
205   return (int)((time.QuadPart/SECONDS_TO_FILETIME)%SECONDS_PER_DAY)/SECONDS_PER_HOUR;
206 }
207
208 int CDateTimeSpan::GetMinutes() const
209 {
210   ULARGE_INTEGER time;
211   ToULargeInt(time);
212
213   return (int)((time.QuadPart/SECONDS_TO_FILETIME%SECONDS_PER_DAY)%SECONDS_PER_HOUR)/SECONDS_PER_MINUTE;
214 }
215
216 int CDateTimeSpan::GetSeconds() const
217 {
218   ULARGE_INTEGER time;
219   ToULargeInt(time);
220
221   return (int)(((time.QuadPart/SECONDS_TO_FILETIME%SECONDS_PER_DAY)%SECONDS_PER_HOUR)%SECONDS_PER_MINUTE)%SECONDS_PER_MINUTE;
222 }
223
224 int CDateTimeSpan::GetSecondsTotal() const
225 {
226   ULARGE_INTEGER time;
227   ToULargeInt(time);
228   
229   return (int)(time.QuadPart/SECONDS_TO_FILETIME);
230 }
231
232 void CDateTimeSpan::SetFromPeriod(const CStdString &period)
233 {
234   long days = atoi(period.c_str());
235   // find the first non-space and non-number
236   size_t pos = period.find_first_not_of("0123456789 ", 0);
237   if (pos != std::string::npos)
238   {
239     CStdString units = period.substr(pos, 3);
240     if (StringUtils::EqualsNoCase(units, "wee"))
241       days *= 7;
242     else if (StringUtils::EqualsNoCase(units, "mon"))
243       days *= 31;
244   }
245
246   SetDateTimeSpan(days, 0, 0, 0);
247 }
248
249 /////////////////////////////////////////////////
250 //
251 // CDateTime
252 //
253
254 CDateTime::CDateTime()
255 {
256   Reset();
257 }
258
259 CDateTime::CDateTime(const SYSTEMTIME &time)
260 {
261   // we store internally as a FILETIME
262   m_state = ToFileTime(time, m_time) ? valid : invalid;
263 }
264
265 CDateTime::CDateTime(const FILETIME &time)
266 {
267   m_time=time;
268   SetValid(true);
269 }
270
271 CDateTime::CDateTime(const CDateTime& time)
272 {
273   m_time=time.m_time;
274   m_state=time.m_state;
275 }
276
277 CDateTime::CDateTime(const time_t& time)
278 {
279   m_state = ToFileTime(time, m_time) ? valid : invalid;
280 }
281
282 CDateTime::CDateTime(const tm& time)
283 {
284   m_state = ToFileTime(time, m_time) ? valid : invalid;
285 }
286
287 CDateTime::CDateTime(int year, int month, int day, int hour, int minute, int second)
288 {
289   SetDateTime(year, month, day, hour, minute, second);
290 }
291
292 CDateTime CDateTime::GetCurrentDateTime()
293 {
294   // get the current time
295   SYSTEMTIME time;
296   GetLocalTime(&time);
297
298   return CDateTime(time);
299 }
300
301 CDateTime CDateTime::GetUTCDateTime()
302 {
303   CDateTime time(GetCurrentDateTime());
304   time += GetTimezoneBias();
305   return time;
306 }
307
308 const CDateTime& CDateTime::operator =(const SYSTEMTIME& right)
309 {
310   m_state = ToFileTime(right, m_time) ? valid : invalid;
311
312   return *this;
313 }
314
315 const CDateTime& CDateTime::operator =(const FILETIME& right)
316 {
317   m_time=right;
318   SetValid(true);
319
320   return *this;
321 }
322
323 const CDateTime& CDateTime::operator =(const time_t& right)
324 {
325   m_state = ToFileTime(right, m_time) ? valid : invalid;
326
327   return *this;
328 }
329
330 const CDateTime& CDateTime::operator =(const tm& right)
331 {
332   m_state = ToFileTime(right, m_time) ? valid : invalid;
333
334   return *this;
335 }
336
337 bool CDateTime::operator >(const CDateTime& right) const
338 {
339   return operator >(right.m_time);
340 }
341
342 bool CDateTime::operator >=(const CDateTime& right) const
343 {
344   return operator >(right) || operator ==(right);
345 }
346
347 bool CDateTime::operator <(const CDateTime& right) const
348 {
349   return operator <(right.m_time);
350 }
351
352 bool CDateTime::operator <=(const CDateTime& right) const
353 {
354   return operator <(right) || operator ==(right);
355 }
356
357 bool CDateTime::operator ==(const CDateTime& right) const
358 {
359   return operator ==(right.m_time);
360 }
361
362 bool CDateTime::operator !=(const CDateTime& right) const
363 {
364   return !operator ==(right);
365 }
366
367 bool CDateTime::operator >(const FILETIME& right) const
368 {
369   return CompareFileTime(&m_time, &right)>0;
370 }
371
372 bool CDateTime::operator >=(const FILETIME& right) const
373 {
374   return operator >(right) || operator ==(right);
375 }
376
377 bool CDateTime::operator <(const FILETIME& right) const
378 {
379   return CompareFileTime(&m_time, &right)<0;
380 }
381
382 bool CDateTime::operator <=(const FILETIME& right) const
383 {
384   return operator <(right) || operator ==(right);
385 }
386
387 bool CDateTime::operator ==(const FILETIME& right) const
388 {
389   return CompareFileTime(&m_time, &right)==0;
390 }
391
392 bool CDateTime::operator !=(const FILETIME& right) const
393 {
394   return !operator ==(right);
395 }
396
397 bool CDateTime::operator >(const SYSTEMTIME& right) const
398 {
399   FILETIME time;
400   ToFileTime(right, time);
401
402   return operator >(time);
403 }
404
405 bool CDateTime::operator >=(const SYSTEMTIME& right) const
406 {
407   return operator >(right) || operator ==(right);
408 }
409
410 bool CDateTime::operator <(const SYSTEMTIME& right) const
411 {
412   FILETIME time;
413   ToFileTime(right, time);
414
415   return operator <(time);
416 }
417
418 bool CDateTime::operator <=(const SYSTEMTIME& right) const
419 {
420   return operator <(right) || operator ==(right);
421 }
422
423 bool CDateTime::operator ==(const SYSTEMTIME& right) const
424 {
425   FILETIME time;
426   ToFileTime(right, time);
427
428   return operator ==(time);
429 }
430
431 bool CDateTime::operator !=(const SYSTEMTIME& right) const
432 {
433   return !operator ==(right);
434 }
435
436 bool CDateTime::operator >(const time_t& right) const
437 {
438   FILETIME time;
439   ToFileTime(right, time);
440
441   return operator >(time);
442 }
443
444 bool CDateTime::operator >=(const time_t& right) const
445 {
446   return operator >(right) || operator ==(right);
447 }
448
449 bool CDateTime::operator <(const time_t& right) const
450 {
451   FILETIME time;
452   ToFileTime(right, time);
453
454   return operator <(time);
455 }
456
457 bool CDateTime::operator <=(const time_t& right) const
458 {
459   return operator <(right) || operator ==(right);
460 }
461
462 bool CDateTime::operator ==(const time_t& right) const
463 {
464   FILETIME time;
465   ToFileTime(right, time);
466
467   return operator ==(time);
468 }
469
470 bool CDateTime::operator !=(const time_t& right) const
471 {
472   return !operator ==(right);
473 }
474
475 bool CDateTime::operator >(const tm& right) const
476 {
477   FILETIME time;
478   ToFileTime(right, time);
479
480   return operator >(time);
481 }
482
483 bool CDateTime::operator >=(const tm& right) const
484 {
485   return operator >(right) || operator ==(right);
486 }
487
488 bool CDateTime::operator <(const tm& right) const
489 {
490   FILETIME time;
491   ToFileTime(right, time);
492
493   return operator <(time);
494 }
495
496 bool CDateTime::operator <=(const tm& right) const
497 {
498   return operator <(right) || operator ==(right);
499 }
500
501 bool CDateTime::operator ==(const tm& right) const
502 {
503   FILETIME time;
504   ToFileTime(right, time);
505
506   return operator ==(time);
507 }
508
509 bool CDateTime::operator !=(const tm& right) const
510 {
511   return !operator ==(right);
512 }
513
514 CDateTime CDateTime::operator +(const CDateTimeSpan& right) const
515 {
516   CDateTime left(*this);
517
518   ULARGE_INTEGER timeLeft;
519   left.ToULargeInt(timeLeft);
520
521   ULARGE_INTEGER timeRight;
522   right.ToULargeInt(timeRight);
523
524   timeLeft.QuadPart+=timeRight.QuadPart;
525
526   left.FromULargeInt(timeLeft);
527
528   return left;
529 }
530
531 CDateTime CDateTime::operator -(const CDateTimeSpan& right) const
532 {
533   CDateTime left(*this);
534
535   ULARGE_INTEGER timeLeft;
536   left.ToULargeInt(timeLeft);
537
538   ULARGE_INTEGER timeRight;
539   right.ToULargeInt(timeRight);
540
541   timeLeft.QuadPart-=timeRight.QuadPart;
542
543   left.FromULargeInt(timeLeft);
544
545   return left;
546 }
547
548 const CDateTime& CDateTime::operator +=(const CDateTimeSpan& right)
549 {
550   ULARGE_INTEGER timeThis;
551   ToULargeInt(timeThis);
552
553   ULARGE_INTEGER timeRight;
554   right.ToULargeInt(timeRight);
555
556   timeThis.QuadPart+=timeRight.QuadPart;
557
558   FromULargeInt(timeThis);
559
560   return *this;
561 }
562
563 const CDateTime& CDateTime::operator -=(const CDateTimeSpan& right)
564 {
565   ULARGE_INTEGER timeThis;
566   ToULargeInt(timeThis);
567
568   ULARGE_INTEGER timeRight;
569   right.ToULargeInt(timeRight);
570
571   timeThis.QuadPart-=timeRight.QuadPart;
572
573   FromULargeInt(timeThis);
574
575   return *this;
576 }
577
578 CDateTimeSpan CDateTime::operator -(const CDateTime& right) const
579 {
580   CDateTimeSpan left;
581
582   ULARGE_INTEGER timeLeft;
583   left.ToULargeInt(timeLeft);
584
585   ULARGE_INTEGER timeThis;
586   ToULargeInt(timeThis);
587
588   ULARGE_INTEGER timeRight;
589   right.ToULargeInt(timeRight);
590
591   timeLeft.QuadPart=timeThis.QuadPart-timeRight.QuadPart;
592
593   left.FromULargeInt(timeLeft);
594
595   return left;
596 }
597
598 CDateTime::operator FILETIME() const
599 {
600   return m_time;
601 }
602
603 void CDateTime::Archive(CArchive& ar)
604 {
605   if (ar.IsStoring())
606   {
607     ar<<(int)m_state;
608     if (m_state==valid)
609     {
610       SYSTEMTIME st;
611       GetAsSystemTime(st);
612       ar<<st;
613     }
614   }
615   else
616   {
617     Reset();
618     int state;
619     ar >> (int &)state;
620     m_state = CDateTime::STATE(state);
621     if (m_state==valid)
622     {
623       SYSTEMTIME st;
624       ar>>st;
625       ToFileTime(st, m_time);
626     }
627   }
628 }
629
630 void CDateTime::Reset()
631 {
632   SetDateTime(1601, 1, 1, 0, 0, 0);
633   SetValid(false);
634 }
635
636 void CDateTime::SetValid(bool yesNo)
637 {
638   m_state=yesNo ? valid : invalid;
639 }
640
641 bool CDateTime::IsValid() const
642 {
643   return m_state==valid;
644 }
645
646 bool CDateTime::ToFileTime(const SYSTEMTIME& time, FILETIME& fileTime) const
647 {
648   return SystemTimeToFileTime(&time, &fileTime) == TRUE &&
649          (fileTime.dwLowDateTime > 0 || fileTime.dwHighDateTime > 0);
650 }
651
652 bool CDateTime::ToFileTime(const time_t& time, FILETIME& fileTime) const
653 {
654   LONGLONG ll = Int32x32To64(time, 10000000)+0x19DB1DED53E8000LL;
655
656   fileTime.dwLowDateTime  = (DWORD)(ll & 0xFFFFFFFF);
657   fileTime.dwHighDateTime = (DWORD)(ll >> 32);
658
659   return true;
660 }
661
662 bool CDateTime::ToFileTime(const tm& time, FILETIME& fileTime) const
663 {
664   SYSTEMTIME st;
665   ZeroMemory(&st, sizeof(SYSTEMTIME));
666
667   st.wYear=time.tm_year+1900;
668   st.wMonth=time.tm_mon+1;
669   st.wDayOfWeek=time.tm_wday;
670   st.wDay=time.tm_mday;
671   st.wHour=time.tm_hour;
672   st.wMinute=time.tm_min;
673   st.wSecond=time.tm_sec;
674
675   return SystemTimeToFileTime(&st, &fileTime)==TRUE;
676 }
677
678 void CDateTime::ToULargeInt(ULARGE_INTEGER& time) const
679 {
680   time.u.HighPart=m_time.dwHighDateTime;
681   time.u.LowPart=m_time.dwLowDateTime;
682 }
683
684 void CDateTime::FromULargeInt(const ULARGE_INTEGER& time)
685 {
686   m_time.dwHighDateTime=time.u.HighPart;
687   m_time.dwLowDateTime=time.u.LowPart;
688 }
689
690 void CDateTime::SetFromDateString(const CStdString &date)
691 {
692   /* TODO:STRING_CLEANUP */
693   if (date.empty())
694   {
695     SetValid(false);
696     return;
697   }
698
699   const char* months[] = {"january","february","march","april","may","june","july","august","september","october","november","december",NULL};
700   int j=0;
701   size_t iDayPos = date.find("day");
702   size_t iPos = date.find(" ");
703   if (iDayPos < iPos && iDayPos != std::string::npos)
704   {
705     iDayPos = iPos + 1;
706     iPos = date.find(" ", iPos+1);
707   }
708   else
709     iDayPos = 0;
710
711   CStdString strMonth = date.substr(iDayPos, iPos - iDayPos);
712   if (strMonth.empty()) // assume dbdate format
713   {
714     SetFromDBDate(date);
715     return;
716   }
717
718   size_t iPos2 = date.find(",");
719   CStdString strDay = (date.size() >= iPos) ? date.substr(iPos, iPos2-iPos) : "";
720   CStdString strYear = date.substr(date.find(" ", iPos2) + 1);
721   while (months[j] && stricmp(strMonth.c_str(),months[j]) != 0)
722     j++;
723   if (!months[j])
724     return;
725
726   SetDateTime(atol(strYear.c_str()),j+1,atol(strDay.c_str()),0,0,0);
727 }
728
729 int CDateTime::GetDay() const
730 {
731   SYSTEMTIME st;
732   GetAsSystemTime(st);
733
734   return st.wDay;
735 }
736
737 int CDateTime::GetMonth() const
738 {
739   SYSTEMTIME st;
740   GetAsSystemTime(st);
741
742   return st.wMonth;
743 }
744
745 int CDateTime::GetYear() const
746 {
747   SYSTEMTIME st;
748   GetAsSystemTime(st);
749
750   return st.wYear;
751 }
752
753 int CDateTime::GetHour() const
754 {
755   SYSTEMTIME st;
756   GetAsSystemTime(st);
757
758   return st.wHour;
759 }
760
761 int CDateTime::GetMinute() const
762 {
763   SYSTEMTIME st;
764   GetAsSystemTime(st);
765
766   return st.wMinute;
767 }
768
769 int CDateTime::GetSecond() const
770 {
771   SYSTEMTIME st;
772   GetAsSystemTime(st);
773
774   return st.wSecond;
775 }
776
777 int CDateTime::GetDayOfWeek() const
778 {
779   SYSTEMTIME st;
780   GetAsSystemTime(st);
781
782   return st.wDayOfWeek;
783 }
784
785 int CDateTime::GetMinuteOfDay() const
786 {
787   SYSTEMTIME st;
788   GetAsSystemTime(st);
789   return st.wHour*60+st.wMinute;
790 }
791
792 void CDateTime::SetDateTime(int year, int month, int day, int hour, int minute, int second)
793 {
794   SYSTEMTIME st;
795   ZeroMemory(&st, sizeof(SYSTEMTIME));
796
797   st.wYear=year;
798   st.wMonth=month;
799   st.wDay=day;
800   st.wHour=hour;
801   st.wMinute=minute;
802   st.wSecond=second;
803
804   m_state = ToFileTime(st, m_time) ? valid : invalid;
805 }
806
807 void CDateTime::SetDate(int year, int month, int day)
808 {
809   SetDateTime(year, month, day, 0, 0, 0);
810 }
811
812 void CDateTime::SetTime(int hour, int minute, int second)
813 {
814   // 01.01.1601 00:00:00 is 0 as filetime
815   SetDateTime(1601, 1, 1, hour, minute, second);
816 }
817
818 void CDateTime::GetAsSystemTime(SYSTEMTIME& time) const
819 {
820   FileTimeToSystemTime(&m_time, &time);
821 }
822
823 #define UNIX_BASE_TIME 116444736000000000LL /* nanoseconds since epoch */
824 void CDateTime::GetAsTime(time_t& time) const
825 {
826   LONGLONG ll;
827   ll = ((LONGLONG)m_time.dwHighDateTime << 32) + m_time.dwLowDateTime;
828   time=(time_t)((ll - UNIX_BASE_TIME) / 10000000);
829 }
830
831 void CDateTime::GetAsTm(tm& time) const
832 {
833   SYSTEMTIME st;
834   GetAsSystemTime(st);
835
836   time.tm_year=st.wYear-1900;
837   time.tm_mon=st.wMonth-1;
838   time.tm_wday=st.wDayOfWeek;
839   time.tm_mday=st.wDay;
840   time.tm_hour=st.wHour;
841   time.tm_min=st.wMinute;
842   time.tm_sec=st.wSecond;
843
844   mktime(&time);
845 }
846
847 void CDateTime::GetAsTimeStamp(FILETIME& time) const
848 {
849   ::LocalFileTimeToFileTime(&m_time, &time);
850 }
851
852 CStdString CDateTime::GetAsDBDate() const
853 {
854   SYSTEMTIME st;
855   GetAsSystemTime(st);
856
857   return StringUtils::Format("%04i-%02i-%02i", st.wYear, st.wMonth, st.wDay);
858 }
859
860 CStdString CDateTime::GetAsDBDateTime() const
861 {
862   SYSTEMTIME st;
863   GetAsSystemTime(st);
864
865   return StringUtils::Format("%04i-%02i-%02i %02i:%02i:%02i", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
866 }
867
868 CStdString CDateTime::GetAsSaveString() const
869 {
870   SYSTEMTIME st;
871   GetAsSystemTime(st);
872
873   return StringUtils::Format("%04i%02i%02i_%02i%02i%02i", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);;
874 }
875
876 void CDateTime::SetFromUTCDateTime(const CDateTime &dateTime)
877 {
878   CDateTime tmp(dateTime);
879   tmp -= GetTimezoneBias();
880
881   m_time = tmp.m_time;
882   m_state = tmp.m_state;
883 }
884
885 static bool bGotTimezoneBias = false;
886
887 void CDateTime::ResetTimezoneBias(void)
888 {
889   bGotTimezoneBias = false;
890 }
891
892 CDateTimeSpan CDateTime::GetTimezoneBias(void)
893 {
894   static CDateTimeSpan timezoneBias;
895
896   if (!bGotTimezoneBias)
897   {
898     bGotTimezoneBias = true;
899     TIME_ZONE_INFORMATION tz;
900     switch(GetTimeZoneInformation(&tz))
901     {
902       case TIME_ZONE_ID_DAYLIGHT:
903         timezoneBias = CDateTimeSpan(0, 0, tz.Bias + tz.DaylightBias, 0);
904         break;
905       case TIME_ZONE_ID_STANDARD:
906         timezoneBias = CDateTimeSpan(0, 0, tz.Bias + tz.StandardBias, 0);
907         break;
908       case TIME_ZONE_ID_UNKNOWN:
909         timezoneBias = CDateTimeSpan(0, 0, tz.Bias, 0);
910         break;
911     }
912   }
913
914   return timezoneBias;
915 }
916
917 void CDateTime::SetFromUTCDateTime(const time_t &dateTime)
918 {
919   CDateTime tmp(dateTime);
920   SetFromUTCDateTime(tmp);
921 }
922
923 void CDateTime::SetFromW3CDate(const CStdString &dateTime)
924 {
925   CStdString date, time, zone;
926
927   size_t posT = dateTime.find("T");
928   if(posT != std::string::npos)
929   {
930     date = dateTime.substr(0, posT);
931     CStdString::size_type posZ = dateTime.find_first_of("+-Z", posT);
932     if(posZ == CStdString::npos)
933       time = dateTime.substr(posT + 1);
934     else
935     {
936       time = dateTime.substr(posT + 1, posZ - posT - 1);
937       zone = dateTime.substr(posZ);
938     }
939   }
940   else
941     date = dateTime;
942
943   int year = 0, month = 1, day = 1, hour = 0, min = 0, sec = 0;
944
945   if (date.size() >= 4)
946     year  = atoi(date.substr(0, 4).c_str());
947
948   if (date.size() >= 10)
949   {
950     month = atoi(date.substr(5, 2).c_str());
951     day   = atoi(date.substr(8, 2).c_str());
952   }
953
954   if (time.length() >= 5)
955   {
956     hour = atoi(time.substr(0, 2).c_str());
957     min  = atoi(time.substr(3, 2).c_str());
958   }
959
960   if (time.length() >= 8)
961     sec  = atoi(time.substr(6, 2).c_str());
962
963   SetDateTime(year, month, day, hour, min, sec);
964 }
965
966 void CDateTime::SetFromDBDateTime(const CStdString &dateTime)
967 {
968   // assumes format YYYY-MM-DD HH:MM:SS
969   if (dateTime.size() == 19)
970   {
971     int year  = atoi(dateTime.substr(0, 4).c_str());
972     int month = atoi(dateTime.substr(5, 2).c_str());
973     int day   = atoi(dateTime.substr(8, 2).c_str());
974     int hour  = atoi(dateTime.substr(11, 2).c_str());
975     int min   = atoi(dateTime.substr(14, 2).c_str());
976     int sec   = atoi(dateTime.substr(17, 2).c_str());
977     SetDateTime(year, month, day, hour, min, sec);
978   }
979 }
980
981 void CDateTime::SetFromDBDate(const CStdString &date)
982 {
983   if (date.size() < 10)
984     return;
985   // assumes format:
986   // YYYY-MM-DD or DD-MM-YYYY
987   int year = 0, month = 0, day = 0;
988   if (date[2] == '-' || date[2] == '.')
989   {
990     day = atoi(date.substr(0, 2).c_str());
991     month = atoi(date.substr(3, 2).c_str());
992     year = atoi(date.substr(6, 4).c_str());
993   }
994   else
995   {
996     year = atoi(date.substr(0, 4).c_str());
997     month = atoi(date.substr(5, 2).c_str());
998     day = atoi(date.substr(8, 2).c_str());
999   }
1000   SetDate(year, month, day);
1001 }
1002
1003 void CDateTime::SetFromDBTime(const CStdString &time)
1004 {
1005   if (time.size() < 8)
1006     return;
1007   // assumes format:
1008   // HH:MM:SS
1009   int hour, minute, second;
1010
1011   hour   = atoi(time.substr(0, 2).c_str());
1012   minute = atoi(time.substr(3, 2).c_str());
1013   second = atoi(time.substr(6, 2).c_str());
1014
1015   SetTime(hour, minute, second);
1016 }
1017
1018 void CDateTime::SetFromRFC1123DateTime(const CStdString &dateTime)
1019 {
1020   CStdString date = dateTime;
1021   StringUtils::Trim(date);
1022
1023   if (date.size() != 29)
1024     return;
1025
1026   int day  = strtol(date.substr(5, 2).c_str(), NULL, 10);
1027
1028   CStdString strMonth = date.substr(8, 3);
1029   int month = 0;
1030   for (unsigned int index = 0; index < 12; index++)
1031   {
1032     if (strMonth.Equals(MONTH_NAMES[index]))
1033     {
1034       month = index + 1;
1035       break;
1036     }
1037   }
1038
1039   if (month < 1)
1040     return;
1041
1042   int year = strtol(date.substr(12, 4).c_str(), NULL, 10);
1043   int hour = strtol(date.substr(17, 2).c_str(), NULL, 10);
1044   int min  = strtol(date.substr(20, 2).c_str(), NULL, 10);
1045   int sec  = strtol(date.substr(23, 2).c_str(), NULL, 10);
1046
1047   SetDateTime(year, month, day, hour, min, sec);
1048 }
1049
1050 CStdString CDateTime::GetAsLocalizedTime(const CStdString &format, bool withSeconds) const
1051 {
1052   CStdString strOut;
1053   const CStdString& strFormat = format.empty() ? g_langInfo.GetTimeFormat() : format;
1054
1055   SYSTEMTIME dateTime;
1056   GetAsSystemTime(dateTime);
1057
1058   // Prefetch meridiem symbol
1059   const CStdString& strMeridiem=g_langInfo.GetMeridiemSymbol(dateTime.wHour > 11 ? CLangInfo::MERIDIEM_SYMBOL_PM : CLangInfo::MERIDIEM_SYMBOL_AM);
1060
1061   size_t length = strFormat.size();
1062   for (size_t i=0; i < length; ++i)
1063   {
1064     char c=strFormat[i];
1065     if (c=='\'')
1066     {
1067       // To be able to display a "'" in the string,
1068       // find the last "'" that doesn't follow a "'"
1069       size_t pos=i + 1;
1070       while(((pos = strFormat.find(c, pos + 1)) != std::string::npos &&
1071              pos<strFormat.size()) && strFormat[pos+1]=='\'') {}
1072
1073       CStdString strPart;
1074       if (pos != std::string::npos)
1075       {
1076         // Extract string between ' '
1077         strPart=strFormat.substr(i + 1, pos - i - 1);
1078         i=pos;
1079       }
1080       else
1081       {
1082         strPart=strFormat.substr(i + 1, length - i - 1);
1083         i=length;
1084       }
1085
1086       StringUtils::Replace(strPart, "''", "'");
1087
1088       strOut+=strPart;
1089     }
1090     else if (c=='h' || c=='H') // parse hour (H="24 hour clock")
1091     {
1092       int partLength=0;
1093
1094       int pos=strFormat.find_first_not_of(c,i+1);
1095       if (pos>-1)
1096       {
1097         // Get length of the hour mask, eg. HH
1098         partLength=pos-i;
1099         i=pos-1;
1100       }
1101       else
1102       {
1103         // mask ends at the end of the string, extract it
1104         partLength=length-i;
1105         i=length;
1106       }
1107
1108       int hour=dateTime.wHour;
1109       if (c=='h')
1110       { // recalc to 12 hour clock
1111         if (hour > 11)
1112           hour -= (12 * (hour > 12));
1113         else
1114           hour += (12 * (hour < 1));
1115       }
1116
1117       // Format hour string with the length of the mask
1118       CStdString str;
1119       if (partLength==1)
1120         str = StringUtils::Format("%d", hour);
1121       else
1122         str = StringUtils::Format("%02d", hour);
1123
1124       strOut+=str;
1125     }
1126     else if (c=='m') // parse minutes
1127     {
1128       int partLength=0;
1129
1130       int pos=strFormat.find_first_not_of(c,i+1);
1131       if (pos>-1)
1132       {
1133         // Get length of the minute mask, eg. mm
1134         partLength=pos-i;
1135         i=pos-1;
1136       }
1137       else
1138       {
1139         // mask ends at the end of the string, extract it
1140         partLength=length-i;
1141         i=length;
1142       }
1143
1144       // Format minute string with the length of the mask
1145       CStdString str;
1146       if (partLength==1)
1147         str = StringUtils::Format("%d", dateTime.wMinute);
1148       else
1149         str = StringUtils::Format("%02d", dateTime.wMinute);
1150
1151       strOut+=str;
1152     }
1153     else if (c=='s') // parse seconds
1154     {
1155       int partLength=0;
1156
1157       int pos=strFormat.find_first_not_of(c,i+1);
1158       if (pos>-1)
1159       {
1160         // Get length of the seconds mask, eg. ss
1161         partLength=pos-i;
1162         i=pos-1;
1163       }
1164       else
1165       {
1166         // mask ends at the end of the string, extract it
1167         partLength=length-i;
1168         i=length;
1169       }
1170
1171       if (withSeconds)
1172       {
1173         // Format seconds string with the length of the mask
1174         CStdString str;
1175         if (partLength==1)
1176           str = StringUtils::Format("%d", dateTime.wSecond);
1177         else
1178           str = StringUtils::Format("%02d", dateTime.wSecond);
1179
1180         strOut+=str;
1181       }
1182       else
1183         strOut.erase(strOut.size()-1,1);
1184     }
1185     else if (c=='x') // add meridiem symbol
1186     {
1187       int pos=strFormat.find_first_not_of(c,i+1);
1188       if (pos>-1)
1189       {
1190         // Get length of the meridiem mask
1191         i=pos-1;
1192       }
1193       else
1194       {
1195         // mask ends at the end of the string, extract it
1196         i=length;
1197       }
1198
1199       strOut+=strMeridiem;
1200     }
1201     else // everything else pass to output
1202       strOut+=c;
1203   }
1204
1205   return strOut;
1206 }
1207
1208 CStdString CDateTime::GetAsLocalizedDate(bool longDate/*=false*/, bool withShortNames/*=true*/) const
1209 {
1210   return GetAsLocalizedDate(g_langInfo.GetDateFormat(longDate), withShortNames);
1211 }
1212
1213 CStdString CDateTime::GetAsLocalizedDate(const CStdString &strFormat, bool withShortNames/*=true*/) const
1214 {
1215   CStdString strOut;
1216
1217   SYSTEMTIME dateTime;
1218   GetAsSystemTime(dateTime);
1219
1220   size_t length = strFormat.size();
1221   for (size_t i = 0; i < length; ++i)
1222   {
1223     char c=strFormat[i];
1224     if (c=='\'')
1225     {
1226       // To be able to display a "'" in the string,
1227       // find the last "'" that doesn't follow a "'"
1228       size_t pos = i + 1;
1229       while(((pos = strFormat.find(c, pos + 1)) != std::string::npos &&
1230              pos < strFormat.size()) &&
1231             strFormat[pos + 1] == '\'') {}
1232
1233       CStdString strPart;
1234       if (pos != std::string::npos)
1235       {
1236         // Extract string between ' '
1237         strPart = strFormat.substr(i + 1, pos - i - 1);
1238         i = pos;
1239       }
1240       else
1241       {
1242         strPart = strFormat.substr(i + 1, length - i - 1);
1243         i = length;
1244       }
1245       StringUtils::Replace(strPart, "''", "'");
1246       strOut+=strPart;
1247     }
1248     else if (c=='D' || c=='d') // parse days
1249     {
1250       size_t partLength=0;
1251
1252       size_t pos = strFormat.find_first_not_of(c, i+1);
1253       if (pos != std::string::npos)
1254       {
1255         // Get length of the day mask, eg. DDDD
1256         partLength=pos-i;
1257         i=pos-1;
1258       }
1259       else
1260       {
1261         // mask ends at the end of the string, extract it
1262         partLength=length-i;
1263         i=length;
1264       }
1265
1266       // Format string with the length of the mask
1267       CStdString str;
1268       if (partLength==1) // single-digit number
1269         str = StringUtils::Format("%d", dateTime.wDay);
1270       else if (partLength==2) // two-digit number
1271         str = StringUtils::Format("%02d", dateTime.wDay);
1272       else // Day of week string
1273       {
1274         int wday = dateTime.wDayOfWeek;
1275         if (wday < 1 || wday > 7) wday = 7;
1276         str = g_localizeStrings.Get(((withShortNames || c =='d') ? 40 : 10) + wday);
1277       }
1278       strOut+=str;
1279     }
1280     else if (c=='M' || c=='m') // parse month
1281     {
1282       size_t partLength=0;
1283
1284       size_t pos=strFormat.find_first_not_of(c,i+1);
1285       if (pos != std::string::npos)
1286       {
1287         // Get length of the month mask, eg. MMMM
1288         partLength=pos-i;
1289         i=pos-1;
1290       }
1291       else
1292       {
1293         // mask ends at the end of the string, extract it
1294         partLength=length-i;
1295         i=length;
1296       }
1297
1298       // Format string with the length of the mask
1299       CStdString str;
1300       if (partLength==1) // single-digit number
1301         str = StringUtils::Format("%d", dateTime.wMonth);
1302       else if (partLength==2) // two-digit number
1303         str = StringUtils::Format("%02d", dateTime.wMonth);
1304       else // Month string
1305       {
1306         int wmonth = dateTime.wMonth;
1307         if (wmonth < 1 || wmonth > 12) wmonth = 12;
1308         str = g_localizeStrings.Get(((withShortNames || c =='m') ? 50 : 20) + wmonth);
1309       }
1310       strOut+=str;
1311     }
1312     else if (c=='Y' || c =='y') // parse year
1313     {
1314       size_t partLength = 0;
1315
1316       size_t pos = strFormat.find_first_not_of(c,i+1);
1317       if (pos != std::string::npos)
1318       {
1319         // Get length of the year mask, eg. YYYY
1320         partLength=pos-i;
1321         i=pos-1;
1322       }
1323       else
1324       {
1325         // mask ends at the end of the string, extract it
1326         partLength=length-i;
1327         i=length;
1328       }
1329
1330       // Format string with the length of the mask
1331       CStdString str = StringUtils::Format("%d", dateTime.wYear); // four-digit number
1332       if (partLength <= 2)
1333         str.erase(0, 2); // two-digit number
1334
1335       strOut+=str;
1336     }
1337     else // everything else pass to output
1338       strOut+=c;
1339   }
1340
1341   return strOut;
1342 }
1343
1344 CStdString CDateTime::GetAsLocalizedDateTime(bool longDate/*=false*/, bool withSeconds/*=true*/) const
1345 {
1346   return GetAsLocalizedDate(longDate)+" "+GetAsLocalizedTime("", withSeconds);
1347 }
1348
1349 CDateTime CDateTime::GetAsUTCDateTime() const
1350 {
1351   CDateTime time(m_time);
1352   time += GetTimezoneBias();
1353   return time;
1354 }
1355
1356 CStdString CDateTime::GetAsRFC1123DateTime() const
1357 {
1358   CDateTime time(GetAsUTCDateTime());
1359
1360   int weekDay = time.GetDayOfWeek();
1361   if (weekDay < 0)
1362     weekDay = 0;
1363   else if (weekDay > 6)
1364     weekDay = 6;
1365   if (weekDay != time.GetDayOfWeek())
1366     CLog::Log(LOGWARNING, "Invalid day of week %d in %s", time.GetDayOfWeek(), time.GetAsDBDateTime().c_str());
1367
1368   int month = time.GetMonth();
1369   if (month < 1)
1370     month = 1;
1371   else if (month > 12)
1372     month = 12;
1373   if (month != time.GetMonth())
1374     CLog::Log(LOGWARNING, "Invalid month %d in %s", time.GetMonth(), time.GetAsDBDateTime().c_str());
1375
1376   CStdString result = StringUtils::Format("%s, %02i %s %04i %02i:%02i:%02i GMT", DAY_NAMES[weekDay], time.GetDay(), MONTH_NAMES[month - 1], time.GetYear(), time.GetHour(), time.GetMinute(), time.GetSecond());
1377   return result;
1378 }
1379
1380 int CDateTime::MonthStringToMonthNum(const CStdString& month)
1381 {
1382   const char* months[] = {"january","february","march","april","may","june","july","august","september","october","november","december"};
1383   const char* abr_months[] = {"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"};
1384
1385   int i = 0;
1386   for (; i < 12 && !StringUtils::EqualsNoCase(month, months[i]) && !StringUtils::EqualsNoCase(month, abr_months[i]); i++);
1387   i++;
1388
1389   return i;
1390 }