WSL/SLF GitLab Repository

Date.cc 30.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/***********************************************************************************/
/*  Copyright 2009 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
/***********************************************************************************/
/* This file is part of MeteoIO.
    MeteoIO is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MeteoIO is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with MeteoIO.  If not, see <http://www.gnu.org/licenses/>.
*/
#include <meteoio/Date.h>
19
#include <meteoio/IOUtils.h>
20
#include <cmath>
21
22
23

using namespace std;

24
#ifdef _MSC_VER
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//This is C99, Microsoft should move on and suppport it, it is almost 15 years old!!
double round(const double& x) {
	//middle value point test
	if (ceil(x+0.5) == floor(x+0.5)) {
		const int a = (int)ceil(x);
		if (a%2 == 0) {
			return ceil(x);
		} else {
			return floor(x);
		}
	} else {
		return floor(x+0.5);
	}
}
#endif

41
42
namespace mio {

43
44
const int Date::daysLeapYear[12] = {31,29,31,30,31,30,31,31,30,31,30,31};
const int Date::daysNonLeapYear[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
45
46
47
48
const double Date::DST_shift = 1.0; //in hours
const float Date::MJD_offset = 2400000.5; ///<offset between julian date and modified julian date
const float Date::Unix_offset = 2440587.5; ///<offset between julian date and Unix Epoch time
const float Date::Excel_offset = 2415018.5;  ///<offset between julian date and Excel dates (note that excel invented some days...)
49
const float Date::Matlab_offset = 1721058.5; ///<offset between julian date and Matlab dates
50

51
52
53
const double Date::epsilon=1./(24.*3600.); ///< minimum difference between two dates. 1 second in units of days
//NOTE: For the comparison operators, we assume that dates are positive so we can bypass a call to abs()

54
55
56
57
// CONSTUCTORS
/**
* @brief Default constructor: timezone is set to GMT without DST, julian date is set to 0 (meaning -4713-01-01T12:00)
*/
58
Date::Date() : timezone(0.), gmt_julian(0.),
59
               gmt_year(0), gmt_month(0), gmt_day(0), gmt_hour(0), gmt_minute(0),
60
61
               dst(false), undef(true)
{
62
63
64
65
66
67
68
69
}

/**
* @brief Julian date constructor.
* @param julian_in julian date to set
* @param in_timezone timezone as an offset to GMT (in hours, optional)
* @param in_dst is it DST? (default: no)
*/
70
71
Date::Date(const double& julian_in, const double& in_timezone, const bool& in_dst)
         : timezone(0.), gmt_julian(0.),
72
           gmt_year(0), gmt_month(0), gmt_day(0), gmt_hour(0), gmt_minute(0),
73
           dst(false), undef(true)
74
{
75
76
77
78
79
80
81
82
	setDate(julian_in, in_timezone, in_dst);
}

/**
* @brief Unix date constructor.
* @param in_time unix time (ie: as number of seconds since Unix Epoch, always UTC)
* @param in_dst is it DST? (default: no)
*/
83
84
Date::Date(const time_t& in_time, const bool& in_dst)
         : timezone(in_dst), gmt_julian(0.),
85
           gmt_year(0), gmt_month(0), gmt_day(0), gmt_hour(0), gmt_minute(0),
86
87
           dst(false), undef(true)
{
88
	setDate(in_time, in_dst);
89
90
91
92
93
94
95
96
97
98
99
100
101
}

/**
* @brief Date constructor by elements.
* All values are checked for plausibility.
* @param in_year in 4 digits
* @param in_month please keep in mind that first month of the year is 1 (ie: not 0!)
* @param in_day please keep in mind that first day of the month is 1 (ie: not 0!)
* @param in_hour
* @param in_minute
* @param in_timezone timezone as an offset to GMT (in hours, optional)
* @param in_dst is it DST? (default: no)
*/
102
103
Date::Date(const int& in_year, const int& in_month, const int& in_day, const int& in_hour, const int& in_minute, const double& in_timezone, const bool& in_dst)
         : timezone(in_timezone), gmt_julian(0.),
104
           gmt_year(0), gmt_month(0), gmt_day(0), gmt_hour(0), gmt_minute(0),
105
           dst(false), undef(true)
106
107
108
109
110
111
112
113
114
{
	setDate(in_year, in_month, in_day, in_hour, in_minute, in_timezone, in_dst);
}

// SETTERS
void Date::setUndef(const bool& flag) {
	undef = flag;
}
/**
115
* @brief Set internal gmt time from system time as well as system time zone.
116
117
*/
void Date::setFromSys() {
118
	/*const time_t curr = time(NULL); //current time in UTC
119
	tm local = *localtime(&curr); //convert to local time
120
121
122
123
124
	const double tz = (double)local.tm_gmtoff/3600.; //time zone shift*/

	const time_t curr = time(NULL);// current time in UTC
	tm local = *gmtime(&curr);// current time in UTC, stored as tm
	const time_t utc = (mktime(&local));// convert GMT tm to GMT time_t
125
	double tz = - difftime(utc,curr)/3600.; //time zone shift (sign so that if curr>utc, tz>0)
126
127
128

	setDate( curr ); //Unix time_t setter, always in gmt
	setTimeZone( tz );
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
}

/**
* @brief Set timezone and Daylight Saving Time flag.
* @param in_timezone timezone as an offset to GMT (in hours)
* @param in_dst is it DST?
*/
void Date::setTimeZone(const double& in_timezone, const bool& in_dst) {
//please keep in mind that timezone might be fractional (ie: 15 minutes, etc)
	if(abs(in_timezone) > 12) {
		throw InvalidArgumentException("[E] Time zone can NOT be greater than +/-12!!", AT);
	}

	timezone = in_timezone;
	dst = in_dst;
}

146
147
148
149
150
151
152
153
154
155
/**
* @brief Copy setter.
* @param in_date Date object to copy
*/
void Date::setDate(const Date& in_date)
{
	if(in_date.isUndef()) {
		dst = false;
		undef = true;
	} else {
156
		setDate(in_date.getJulian(), in_date.getTimeZone(), in_date.getDST());
157
158
159
	}
}

160
161
162
/**
* @brief Set date by elements.
* All values are checked for plausibility.
163
164
165
166
167
168
169
* @param i_year in 4 digits
* @param i_month please keep in mind that first month of the year is 1 (ie: not 0!)
* @param i_day please keep in mind that first day of the month is 1 (ie: not 0!)
* @param i_hour
* @param i_minute
* @param i_timezone timezone as an offset to GMT (in hours, optional)
* @param i_dst is it DST? (default: no)
170
*/
171
void Date::setDate(const int& i_year, const int& i_month, const int& i_day, const int& i_hour, const int& i_minute, const double& i_timezone, const bool& i_dst)
172
{
173
	plausibilityCheck(i_year, i_month, i_day, i_hour, i_minute); //also checks leap years
174
	setTimeZone(i_timezone, i_dst);
175
176
177
178

	if(timezone==0 && dst==false) {
		//data is GMT and no DST
		//setting values and computing GMT julian date
179
		gmt_julian = calculateJulianDate(i_year, i_month, i_day, i_hour, i_minute);
180
181
	} else {
		//computing local julian date
182
		const double local_julian = calculateJulianDate(i_year, i_month, i_day, i_hour, i_minute);
183
184
185
		//converting local julian date to GMT julian date
		gmt_julian = localToGMT(local_julian);
	}
186
187
	//updating values to GMT, fixing potential 24:00 hour (ie: replaced by next day, 00:00)
	calculateValues(gmt_julian, gmt_year, gmt_month, gmt_day, gmt_hour, gmt_minute);
188
	undef = false;
189
190
}

191
void Date::setDate(const int& year, const unsigned int& month, const unsigned int& day, const unsigned int& hour, const unsigned int& minute, const double& in_timezone, const bool& in_dst)
192
193
194
195
{
	setDate(year, (signed)month, (signed)day, (signed)hour, (signed)minute, in_timezone, in_dst);
}

196
197
198
199
200
201
202
203
204
/**
* @brief Set date from a julian date (JD).
* @param julian_in julian date to set
* @param in_timezone timezone as an offset to GMT (in hours, optional)
* @param in_dst is it DST? (default: no)
*/
void Date::setDate(const double& julian_in, const double& in_timezone, const bool& in_dst) {
	setTimeZone(in_timezone, in_dst);
	gmt_julian = localToGMT(julian_in);
205
	calculateValues(gmt_julian, gmt_year, gmt_month, gmt_day, gmt_hour, gmt_minute);
206
	undef = false;
207
208
209
210
}

/**
* @brief Set date from a Unix date.
211
212
* @param i_time unix time (ie: as number of seconds since Unix Epoch, always UTC)
* @param i_dst is it DST? (default: no)
213
*/
214
215
void Date::setDate(const time_t& i_time, const bool& i_dst) {
	setUnixDate(i_time, i_dst);
216
217
218
219
220
}

/**
* @brief Set date from a modified julian date (MJD).
* @param julian_in julian date to set
221
222
* @param i_timezone timezone as an offset to GMT (in hours, optional)
* @param i_dst is it DST? (default: no)
223
*/
224
225
226
void Date::setModifiedJulianDate(const double& julian_in, const double& i_timezone, const bool& i_dst) {
	const double tmp_julian = julian_in + MJD_offset;
	setDate(tmp_julian, i_timezone, i_dst);
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
}

/**
* @brief Set date from a Unix date.
* @param in_time unix time (ie: as number of seconds since Unix Epoch, always UTC)
* @param in_dst is it DST? (default: no)
*/
void Date::setUnixDate(const time_t& in_time, const bool& in_dst) {
	const double in_julian = (double)(in_time)/(24.*60.*60.) + Unix_offset;
	setDate(in_julian, 0., in_dst);
}

/**
* @brief Set date from an Excel date.
* @param excel_in Excel date to set
242
243
* @param i_timezone timezone as an offset to GMT (in hours, optional)
* @param i_dst is it DST? (default: no)
244
*/
245
void Date::setExcelDate(const double excel_in, const double& i_timezone, const bool& i_dst) {
246
	//TODO: handle date < 1900-01-00 and date before 1900-03-01
247
	//see http://www.mathworks.com/help/toolbox/finance/x2mdate.html
248
249
	const double tmp_julian = excel_in + Excel_offset;
	setDate(tmp_julian, i_timezone, i_dst);
250
251
}

252
253
254
/**
* @brief Set date from an Matlab date.
* @param matlab_in Matlab date to set
255
256
* @param i_timezone timezone as an offset to GMT (in hours, optional)
* @param i_dst is it DST? (default: no)
257
*/
258
259
260
void Date::setMatlabDate(const double matlab_in, const double& i_timezone, const bool& i_dst) {
	const double tmp_julian = matlab_in + Matlab_offset;
	setDate(tmp_julian, i_timezone, i_dst);
261
262
263
}


264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
// GETTERS
bool Date::isUndef() const {
	return undef;
}

/**
* @brief Returns timezone.
* @return timezone as an offset to GMT
*/
double Date::getTimeZone() const {
	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

	return timezone;
}

/**
* @brief Returns Daylight Saving Time flag.
* @return dst enabled?
*/
bool Date::getDST() const {
	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

	return dst;
}

/**
* @brief Return julian date (JD).
* The julian date is defined as the fractional number of days since -4713-01-01T12:00 UTC.
* @param gmt convert returned value to GMT? (default: false)
* @return julian date in the current timezone / in GMT depending on the gmt parameter
*/
297
double Date::getJulian(const bool& gmt) const {
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

	if(gmt) {
		return gmt_julian;
	} else {
		const double local_julian = GMTToLocal(gmt_julian);
		return local_julian;
	}
}

/**
* @brief Return modified julian date (MJD).
* The modified julian date is defined as the fractional number of days since 1858-11-17T00:00 UTC
* (definition by the Smithsonian Astrophysical Observatory, MA).
* @param gmt convert returned value to GMT? (default: false)
* @return modified julian date in the current timezone / in GMT depending on the gmt parameter
*/
double Date::getModifiedJulianDate(const bool& gmt) const {
	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

	if(gmt) {
		return (gmt_julian - MJD_offset);
	} else {
		const double local_julian = GMTToLocal(gmt_julian);
		return (local_julian - MJD_offset);
	}
}

/**
* @brief Return truncated julian date (TJD).
* The truncated julian date is defined as the julian day shifted to start at 00:00 and modulo 10000 days.
331
* The last origin (ie: 0) was 1995-10-10T00:00
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
* (definition by National Institute of Standards and Technology).
* @param gmt convert returned value to GMT? (default: false)
* @return truncated julian date in the current timezone / in GMT depending on the gmt parameter
*/
double Date::getTruncatedJulianDate(const bool& gmt) const {
	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

	if(gmt) {
		return (fmod( (gmt_julian - 0.5), 10000. ));
	} else {
		const double local_julian = GMTToLocal(gmt_julian);
		return (fmod( (local_julian - 0.5), 10000. ));
	}
}

/**
* @brief Return Unix time (or POSIX time).
* The Unix time is defined as the number of seconds since 1970-01-01T00:00 UTC (Unix Epoch).
351
* It is therefore ALWAYS in GMT.
352
353
354
355
* (defined as IEEE P1003.1 POSIX. See http://www.mail-archive.com/leapsecs@rom.usno.navy.mil/msg00109.html
* for some technical, historical and funny insight into the standardization process)
* @return Unix time in the current timezone / in GMT depending on the gmt parameter
*/
356
time_t Date::getUnixDate() const {
357
358
359
360
	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

	if (gmt_julian < Unix_offset)
361
		throw IOException("Dates before 1970 cannot be displayed in Unix epoch time", AT);
362

363
	return ( (time_t)floor( (gmt_julian - Unix_offset) * (24*60*60) ));
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
}

/**
* @brief Return Excel date.
* The (sick) Excel date is defined as the number of days since 1900-01-00T00:00 (no, this is NOT a typo).
* Moreover, it (wrongly) considers that 1900 was a leap year (in order to remain compatible with an old Lotus123 bug).
* This practically means that for dates after 1900-03-01, an Excel date really represents the number of days since 1900-01-01T00:00 PLUS 2.
* @param gmt convert returned value to GMT? (default: false)
* @return Excel date in the current timezone / in GMT depending on the gmt parameter
*/
double Date::getExcelDate(const bool& gmt) const {
	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

	if (gmt_julian < Excel_offset)
		throw IOException("Dates before 1900 cannot be converted to Excel date", AT);

	if(gmt) {
		return ( gmt_julian - Excel_offset);
	} else {
		const double local_julian = GMTToLocal(gmt_julian);
		return ( local_julian - Excel_offset);
	}
}

389
/**
390
* @brief Return Matlab date.
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
* This is the number of days since 0000-01-01T00:00:00. See http://www.mathworks.com/help/techdoc/ref/datenum.html
* @param gmt convert returned value to GMT? (default: false)
* @return Matlab date in the current timezone / in GMT depending on the gmt parameter
*/
double Date::getMatlabDate(const bool& gmt) const {
	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

	if(gmt) {
		return ( gmt_julian - Matlab_offset);
	} else {
		const double local_julian = GMTToLocal(gmt_julian);
		return ( local_julian - Matlab_offset);
	}
}


408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/**
* @brief Retrieve julian date.
* This method is a candidate for deletion: it should now be obsolete.
* @param julian_out julian date (in local time zone or GMT depending on the gmt flag)
* @param gmt convert returned value to GMT? (default: false)
*/
void Date::getDate(double& julian_out, const bool& gmt) const {
	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

	if(gmt) {
		julian_out = gmt_julian;
	} else {
		const double local_julian = GMTToLocal(gmt_julian);
		julian_out = local_julian;
	}
}

/**
* @brief Return year.
* @param gmt convert returned value to GMT? (default: false)
* @return year
*/
int Date::getYear(const bool& gmt) const {
	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

435
436
437
438
439
440
441
442
	if(gmt) {
		return gmt_year;
	} else {
		const double local_julian = GMTToLocal(gmt_julian);
		int local_year, local_month, local_day, local_hour, local_minute;
		calculateValues(local_julian, local_year, local_month, local_day, local_hour, local_minute);
		return local_year;
	}
443
444
445
446
447
448
449
450
451
452
453
454
455
}

/**
* @brief Return year, month, day.
* @param year_out
* @param month_out
* @param day_out
* @param gmt convert returned value to GMT? (default: false)
*/
void Date::getDate(int& year_out, int& month_out, int& day_out, const bool& gmt) const {
	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

456
457
458
459
460
461
462
463
464
	if(gmt) {
		year_out = gmt_year;
		month_out = gmt_month;
		day_out = gmt_day;
	} else {
		const double local_julian = GMTToLocal(gmt_julian);
		int local_hour, local_minute;
		calculateValues(local_julian, year_out, month_out, day_out, local_hour, local_minute);
	}
465
466
467
468
469
470
471
472
473
474
475
476
477
478
}

/**
* @brief Return year, month, day.
* @param year_out
* @param month_out
* @param day_out
* @param hour_out
* @param gmt convert returned value to GMT? (default: false)
*/
void Date::getDate(int& year_out, int& month_out, int& day_out, int& hour_out, const bool& gmt) const {
	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

479
480
481
482
483
484
485
486
487
488
	if(gmt) {
		year_out = gmt_year;
		month_out = gmt_month;
		day_out = gmt_day;
		hour_out = gmt_hour;
	} else {
		const double local_julian = GMTToLocal(gmt_julian);
		int local_minute;
		calculateValues(local_julian, year_out, month_out, day_out, hour_out, local_minute);
	}
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
}

/**
* @brief Return year, month, day.
* @param year_out
* @param month_out
* @param day_out
* @param hour_out
* @param minute_out
* @param gmt convert returned value to GMT? (default: false)
*/
void Date::getDate(int& year_out, int& month_out, int& day_out, int& hour_out, int& minute_out, const bool& gmt) const {
	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

504
505
506
507
508
509
510
511
512
513
	if(gmt) {
		year_out = gmt_year;
		month_out = gmt_month;
		day_out = gmt_day;
		hour_out = gmt_hour;
		minute_out = gmt_minute;
	} else {
		const double local_julian = GMTToLocal(gmt_julian);
		calculateValues(local_julian, year_out, month_out, day_out, hour_out, minute_out);
	}
514
515
516
}

/**
517
* @brief Return the julian day for the current date.
518
* Return the day of the year index for the current Date object
519
* @param gmt convert returned value to GMT? (default: false)
520
521
* @return julian day number
*/
522
int Date::getJulianDayNumber(const bool& gmt) const {
523
524
525
	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

526
527
528
529
530
531
532
533
534
535
536
	if(gmt) {
		const double first_day_of_year = getJulianDayNumber(gmt_year, 1, 1);
		return (int)(gmt_julian - first_day_of_year + 1);
	} else {
		const double local_julian = GMTToLocal(gmt_julian);
		int local_year, local_month, local_day, local_hour, local_minute;
		calculateValues(local_julian, local_year, local_month, local_day, local_hour, local_minute);
		const double in_day_offset = 1./24.*((double)local_hour+1./60.*(double)local_minute) - 0.5;
		const double first_day_of_year = static_cast<double>(getJulianDayNumber(local_year, 1, 1)) + in_day_offset;
		return (int)(local_julian - first_day_of_year + 1);
	}
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
}

/**
* @brief Return true if the current year is a leap year
* @return true if the current year is a leap year
*/
bool Date::isLeapYear() const {
	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

	//this is quite inefficient... we might want to deal with leap years with their rule instead
	int local_year, local_month, local_day, local_hour, local_minute;
	getDate(local_year, local_month, local_day, local_hour, local_minute);

	return (isLeapYear(local_year));

	/*
	if( ((local_year%4 == 0) && (local_year%100 != 0)) || (local_year%400 == 0) ) {
	return true;
} else {
	return false;
}
	*/
}

/**
 * @brief Round date to a given precision
 * @param precision round date to the given precision, in seconds
 * @param type rounding strategy (default: CLOSEST)
 */
void Date::rnd(const double& precision, const RND& type) {
	if(undef==false) {
		const double rnd_factor = (3600*24)/precision;
		if(type==UP)
			gmt_julian = ceil(gmt_julian*rnd_factor) / rnd_factor;
		if(type==DOWN)
			gmt_julian = floor(gmt_julian*rnd_factor) / rnd_factor;
		if(type==CLOSEST)
			gmt_julian = round(gmt_julian*rnd_factor) / rnd_factor;
	}
}

const Date Date::rnd(const Date& indate, const double& precision, const RND& type) {
580
581
582
	Date tmp(indate);
	tmp.rnd(precision, type);
	return tmp;
583
584
585
586
587
588
589
590
591
}

// OPERATORS //HACK this will have to handle Durations
Date& Date::operator+=(const Date& indate) {
	if(undef==true || indate.isUndef()) {
		undef=true;
		return *this;
	}
	gmt_julian += indate.gmt_julian;
592
	calculateValues(gmt_julian, gmt_year, gmt_month, gmt_day, gmt_hour, gmt_minute);
593
594
595
596
597
598
599
600
601
	return *this;
}

Date& Date::operator-=(const Date& indate) {
	if(undef==true || indate.isUndef()) {
		undef=true;
		return *this;
	}
	gmt_julian -= indate.gmt_julian;
602
	calculateValues(gmt_julian, gmt_year, gmt_month, gmt_day, gmt_hour, gmt_minute);
603
604
605
606
607
608
	return *this;
}

Date& Date::operator+=(const double& indate) {
	if(undef==false) {
		gmt_julian += indate;
609
		calculateValues(gmt_julian, gmt_year, gmt_month, gmt_day, gmt_hour, gmt_minute);
610
611
612
613
614
615
616
	}
	return *this;
}

Date& Date::operator-=(const double& indate) {
	if(undef==false) {
		gmt_julian -= indate;
617
		calculateValues(gmt_julian, gmt_year, gmt_month, gmt_day, gmt_hour, gmt_minute);
618
619
620
621
622
623
624
	}
	return *this;
}

Date& Date::operator*=(const double& value) {
	if(undef==false) {
		gmt_julian *= value;
625
		calculateValues(gmt_julian, gmt_year, gmt_month, gmt_day, gmt_hour, gmt_minute);
626
627
628
629
630
631
632
	}
	return *this;
}

Date& Date::operator/=(const double& value) {
	if(undef==false) {
		gmt_julian /= value;
633
		calculateValues(gmt_julian, gmt_year, gmt_month, gmt_day, gmt_hour, gmt_minute);
634
635
636
637
638
639
640
641
	}
	return *this;
}

bool Date::operator==(const Date& indate) const {
	if(undef==true || indate.isUndef()) {
		return( undef==true && indate.isUndef() );
	}
642

643
	return IOUtils::checkEpsilonEquality(gmt_julian, indate.gmt_julian, epsilon);
644
645
646
647
648
649
650
651
652
653
654
}

bool Date::operator!=(const Date& indate) const {
	return !(*this==indate);
}

bool Date::operator<(const Date& indate) const {
	if(undef==true || indate.isUndef()) {
		throw UnknownValueException("Date object is undefined!", AT);
	}

655
656
657
658
#ifdef NEGATIVE_JULIAN
	if(*this==indate) return false;
	return (gmt_julian < indate.gmt_julian);
#else
659
	return (gmt_julian < (indate.gmt_julian-epsilon));
660
#endif
661
662
663
664
665
666
667
}

bool Date::operator<=(const Date& indate) const {
	if(undef==true || indate.isUndef()) {
		throw UnknownValueException("Date object is undefined!", AT);
	}

668
669
670
671
#ifdef NEGATIVE_JULIAN
	if(*this==indate) return true;
	return (gmt_julian <= indate.gmt_julian);
#else
672
	return (gmt_julian <= (indate.gmt_julian+epsilon));
673
#endif
674
675
676
677
678
679
680
}

bool Date::operator>(const Date& indate) const {
	if(undef==true || indate.isUndef()) {
		throw UnknownValueException("Date object is undefined!", AT);
	}

681
682
683
684
#ifdef NEGATIVE_JULIAN
	if(*this==indate) return false;
	return (gmt_julian > indate.gmt_julian);
#else
685
	return (gmt_julian > (indate.gmt_julian+epsilon));
686
#endif
687
688
689
690
691
692
693
}

bool Date::operator>=(const Date& indate) const {
	if(undef==true || indate.isUndef()) {
		throw UnknownValueException("Date object is undefined!", AT);
	}

694
695
696
697
#ifdef NEGATIVE_JULIAN
	if(*this==indate) return true;
	return (gmt_julian >= indate.gmt_julian);
#else
698
	return (gmt_julian >= (indate.gmt_julian-epsilon));
699
#endif
700
701
702
703
704
705
706
707
}

const Date Date::operator+(const Date& indate) const {
	if(undef==true || indate.isUndef()) {
		Date tmp; //create an Undef date
		return tmp;
	}

708
709
	Date tmp(gmt_julian + indate.gmt_julian, 0.);
	tmp.setTimeZone(timezone);
710
711
712
713
714
715
716
717
718
	return tmp;
}

const Date Date::operator-(const Date& indate) const {
	if(undef==true || indate.isUndef()) {
		Date tmp; //create an Undef date
		return tmp;
	}

719
720
	Date tmp(gmt_julian - indate.gmt_julian, 0.);
	tmp.setTimeZone(timezone);
721
722
723
724
725
	return tmp;
}

const Date Date::operator+(const double& indate) const {
	//remains undef if undef
726
727
	Date tmp(gmt_julian + indate, 0.);
	tmp.setTimeZone(timezone);
728
729
730
731
732
	return tmp;
}

const Date Date::operator-(const double& indate) const {
	//remains undef if undef
733
734
	Date tmp(gmt_julian - indate, 0.);
	tmp.setTimeZone(timezone);
735
736
737
738
739
	return tmp;
}

const Date Date::operator*(const double& value) const {
	//remains undef if undef
740
741
	Date tmp(gmt_julian * value, 0.);
	tmp.setTimeZone(timezone);
742
743
744
745
746
	return tmp;
}

const Date Date::operator/(const double& value) const {
	//remains undef if undef
747
748
	Date tmp(gmt_julian / value, 0.);
	tmp.setTimeZone(timezone);
749
750
751
752
753
754
755
756
757
	return tmp;
}

std::ostream& operator<<(std::ostream &os, const Date &date) {
	os << "<date>\n";
	if(date.undef==true)
		os << "Date is undefined\n";
	else {
		os << date.toString(Date::ISO) << "\n";
758
		os << "TZ=GMT" << showpos << date.timezone << noshowpos << "\t\t" << "DST=" << date.dst << "\n";
759
		os << "julian:\t\t\t" << setprecision(10) << date.getJulian() << "\t(GMT=" << date.getJulian(true) << ")\n";
760
761
		os << "ModifiedJulian:\t\t" << date.getModifiedJulianDate() << "\n";
		os << "TruncatedJulian:\t" << date.getTruncatedJulianDate() << "\n";
762
		os << "MatlabJulian:\t\t" << date.getMatlabDate() << "\n";
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
		try {
			os << "Unix:\t\t\t" << date.getUnixDate() << "\n";
		} catch (...) {}
		try {
			os << "Excel:\t\t\t" << date.getExcelDate() << "\n";
		} catch (...) {}
	}
	os << "</date>\n";
	return os;
}

/**
* @brief Return a nicely formated string.
* @param type select the formating to apply (see the definition of Date::FORMATS)
* @param gmt convert returned value to GMT? (default: false)
* @return formatted time in a string
*/
const string Date::toString(FORMATS type, const bool& gmt) const
{//the date are displayed in LOCAL timezone (more user friendly)
782
783
	int year_out, month_out, day_out, hour_out, minute_out;
	double julian_out;
784
785
786
787

	if(undef==true)
		throw UnknownValueException("Date object is undefined!", AT);

788
789
790
791
792
793
794
795
796
797
798
	if(gmt) {
		julian_out = gmt_julian;
		year_out = gmt_year;
		month_out = gmt_month;
		day_out = gmt_day;
		hour_out = gmt_hour;
		minute_out = gmt_minute;
	} else {
		julian_out = GMTToLocal(gmt_julian);
		calculateValues(julian_out, year_out, month_out, day_out, hour_out, minute_out);
	}
799
800
801

	stringstream tmpstr;
	if(type==ISO) {
802
			tmpstr
803
804
805
806
807
808
			<< setw(4) << setfill('0') << year_out << "-"
			<< setw(2) << setfill('0') << month_out << "-"
			<< setw(2) << setfill('0') << day_out << "T"
			<< setw(2) << setfill('0') << hour_out << ":"
			<< setw(2) << setfill('0') << minute_out;
	} else if(type==NUM) {
809
			tmpstr
810
811
812
813
814
815
			<< setw(4) << setfill('0') << year_out
			<< setw(2) << setfill('0') << month_out
			<< setw(2) << setfill('0') << day_out
			<< setw(2) << setfill('0') << hour_out
			<< setw(2) << setfill('0') << minute_out ;
	} else if(type==FULL) {
816
			tmpstr
817
818
819
820
821
822
823
824
			<< setw(4) << setfill('0') << year_out << "-"
			<< setw(2) << setfill('0') << month_out << "-"
			<< setw(2) << setfill('0') << day_out << "T"
			<< setw(2) << setfill('0') << hour_out << ":"
			<< setw(2) << setfill('0') << minute_out << " ("
			<< setprecision(10) << julian_out << ") GMT"
			<< setw(2) << setfill('0') << showpos << timezone << noshowpos;
	} else if(type==DIN) {
825
			tmpstr
826
827
828
829
830
831
832
833
834
835
836
837
838
			<< setw(2) << setfill('0') << day_out << "."
			<< setw(2) << setfill('0') << month_out << "."
			<< setw(4) << setfill('0') << year_out << " "
			<< setw(2) << setfill('0') << hour_out << ":"
			<< setw(2) << setfill('0') << minute_out;
	} else {
		throw InvalidArgumentException("Wrong date conversion format requested", AT);
	}

	return tmpstr.str();
}

// PRIVATE METHODS
839
double Date::calculateJulianDate(const int& i_year, const int& i_month, const int& i_day, const int& i_hour, const int& i_minute) const
840
{
841
842
	const long julday = getJulianDayNumber(i_year, i_month, i_day);
	const double frac = (i_hour-12.)/24. + i_minute/(24.*60.); //the julian date reference is at 12:00
843
844
845
846

	return (((double)julday) + frac);
}

847
void Date::calculateValues(const double& i_julian, int& o_year, int& o_month, int& o_day, int& o_hour, int& o_minute) const
848
{ //given a julian day, calculate the year, month, day, hours and minutes
849
850
851
852
853
 //see Fliegel, H. F. and van Flandern, T. C. 1968. Letters to the editor: a machine algorithm for processing calendar dates. Commun. ACM 11, 10 (Oct. 1968), 657. DOI= http://doi.acm.org/10.1145/364096.364097
	//we round the given julian date to the closest minute since this is our current resolution
	const double rnd_factor = (60.*24.);
	const double tmp_julian = round(i_julian*rnd_factor) / rnd_factor;

854
	long t1;
855
	const long julday = (long) floor(tmp_julian+0.5);
856

857
	t1 = julday + 68569L;
858
859
860
861
862
863
	const long t2 = 4L * t1 / 146097L;
	t1 = t1 - ( 146097L * t2 + 3L ) / 4L;
	const long yr = 4000L * ( t1 + 1L ) / 1461001L;
	t1 = t1 - 1461L * yr / 4L + 31L;
	const long mo = 80L * t1 / 2447L;

864
	o_day = (int) ( t1 - 2447L * mo / 80L );
865
	t1 = mo / 11L;
866
867
	o_month = (int) ( mo + 2L - 12L * t1 );
	o_year = (int) ( 100L * ( t2 - 49L ) + yr + t1 );
868
869

	// Correct for BC years -> astronomical year, that is from year -1 to year 0
870
871
	if ( o_year <= 0 ) {
		o_year--;
872
873
	}

874
	const double frac = (tmp_julian + 0.5) - floor(tmp_julian+0.5); //the julian date reference is at 12:00
875
876
	o_minute = ((int)round(frac*((double)24.0*60.0))) % 60;
	o_hour = (int) round((((double)1440.0)*frac-(double)o_minute)/(double)60.0);
877
878
}

879
bool Date::isLeapYear(const int& i_year) const
880
{
881
882
883
	long jd1, jd2;
	jd1 = getJulianDayNumber( i_year, 2, 28 );
	jd2 = getJulianDayNumber( i_year, 3, 1 );
884
885
886
	return ( (jd2-jd1) > 1 );
}

887
long Date::getJulianDayNumber(const int& i_year, const int& i_month, const int& i_day) const
888
{ //given year, month, day, calculate the matching julian day
889
 //see Fliegel, H. F. and van Flandern, T. C. 1968. Letters to the editor: a machine algorithm for processing calendar dates. Commun. ACM 11, 10 (Oct. 1968), 657. DOI= http://doi.acm.org/10.1145/364096.364097
890
891
	const long lmonth = (long) i_month, lday = (long) i_day;
	long lyear = (long) i_year;
892
893
894
895
896
897
898

	// Correct for BC years -> astronomical year, that is from year -1 to year 0
	if ( lyear < 0 ) {
		lyear++;
	}

	const long jdn = lday - 32075L +
899
900
901
	                  1461L * ( lyear + 4800L + ( lmonth - 14L ) / 12L ) / 4L +
	                  367L * ( lmonth - 2L - ( lmonth - 14L ) / 12L * 12L ) / 12L -
	                  3L * ( ( lyear + 4900L + ( lmonth - 14L ) / 12L ) / 100L ) / 4L;
902
903
904
905
906
907

	return jdn;
}

void Date::plausibilityCheck(const int& in_year, const int& in_month, const int& in_day, const int& in_hour, const int& in_minute) const {
	if ((in_year < -4713) || (in_year >3000)
908
909
910
911
	    || (in_month < 1) || (in_month > 12)
	    || (in_day < 1) || ((in_day > daysNonLeapYear[in_month-1]) && !isLeapYear(in_year))
	    || ((in_day > daysLeapYear[in_month-1]) && isLeapYear(in_year))
	    || (in_hour < 0) || (in_hour > 24)
912
	    || (in_minute < 0) || (in_minute > 59)) {
913
		stringstream ss;
914
915
		ss << "Invalid Date requested: " << in_year << "-" << in_month;
		ss << "-" << in_day << "T" << in_hour << ":" << in_minute;
916
		throw IOException(ss.str(), AT);
917
918
919
	}

	if ((in_hour == 24) && (in_minute != 0)) {
920
		stringstream ss;
921
922
		ss << "Invalid Date requested: " << in_year << "-" << in_month;
		ss << "-" << in_day << "T" << in_hour << ":" << in_minute;
923
		throw IOException(ss.str(), AT);
924
925
926
	}
}

927
double Date::localToGMT(const double& i_julian) const {
928
	if(dst) {
929
		return (i_julian - timezone/24. - DST_shift/24.);
930
	} else {
931
		return (i_julian - timezone/24.);
932
933
934
	}
}

935
double Date::GMTToLocal(const double& i_gmt_julian) const {
936
	if(dst) {
937
		return (i_gmt_julian + timezone/24. + DST_shift/24.);
938
	} else {
939
		return (i_gmt_julian + timezone/24.);
940
941
942
943
944
945
946
947
948
949
	}
}

#ifdef _POPC_
void Date::Serialize(POPBuffer &buf, bool pack)
{
	if (pack) {
		buf.Pack(&timezone,1);
		buf.Pack(&dst,1);
		buf.Pack(&gmt_julian,1);
950
951
952
953
954
		buf.Pack(&gmt_year,1);
		buf.Pack(&gmt_month,1);
		buf.Pack(&gmt_day,1);
		buf.Pack(&gmt_hour,1);
		buf.Pack(&gmt_minute,1);
955
956
957
958
		buf.Pack(&undef,1);
	} else {
		buf.UnPack(&timezone,1);
		buf.UnPack(&dst,1);
959
960
961
962
963
964
		buf.UnPack(&gmt_julian,1);
		buf.UnPack(&gmt_year,1);
		buf.UnPack(&gmt_month,1);
		buf.UnPack(&gmt_day,1);
		buf.UnPack(&gmt_hour,1);
		buf.UnPack(&gmt_minute,1);
965
966
967
968
969
970
		buf.UnPack(&undef,1);
	}
}
#endif

} //namespace