-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathqdatetime.rs
707 lines (612 loc) · 26.2 KB
/
qdatetime.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
297
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
// SPDX-FileCopyrightText: 2022 Klarälvdalens Datakonsult AB, a KDAB Group company <[email protected]>
// SPDX-FileContributor: Andrew Hayzen <[email protected]>
//
// SPDX-License-Identifier: MIT OR Apache-2.0
use cxx::{type_id, ExternType};
use std::mem::MaybeUninit;
use std::{cmp::Ordering, fmt};
use crate::{QDate, QTime};
#[cxx::bridge]
mod ffi {
#[namespace = "Qt"]
unsafe extern "C++" {
include!("cxx-qt-lib/qt.h");
type TimeSpec = crate::TimeSpec;
type DateFormat = crate::DateFormat;
}
unsafe extern "C++" {
include!("cxx-qt-lib/qtypes.h");
type qint64 = crate::qint64;
}
unsafe extern "C++" {
include!("cxx-qt-lib/qdate.h");
type QDate = crate::QDate;
include!("cxx-qt-lib/qdatetime.h");
type QDateTime = super::QDateTime;
include!("cxx-qt-lib/qtime.h");
type QTime = crate::QTime;
include!("cxx-qt-lib/qstring.h");
type QString = crate::QString;
include!("cxx-qt-lib/qtimezone.h");
type QTimeZone = crate::QTimeZone;
/// Returns a QDateTime object containing a datetime ndays days later than the datetime of this object (or earlier if ndays is negative).
#[rust_name = "add_days"]
fn addDays(self: &QDateTime, ndays: qint64) -> QDateTime;
/// Returns a QDateTime object containing a datetime nmonths months later than the datetime of this object (or earlier if nmonths is negative).
#[rust_name = "add_months"]
fn addMonths(self: &QDateTime, nmonths: i32) -> QDateTime;
/// Returns a QDateTime object containing a datetime msecs milliseconds later than the datetime of this object (or earlier if msecs is negative).
#[rust_name = "add_msecs"]
fn addMSecs(self: &QDateTime, msecs: qint64) -> QDateTime;
/// Returns a QDateTime object containing a datetime s seconds later than the datetime of this object (or earlier if s is negative).
#[rust_name = "add_secs"]
fn addSecs(self: &QDateTime, secs: qint64) -> QDateTime;
/// Returns a QDateTime object containing a datetime nyears years later than the datetime of this object (or earlier if nyears is negative).
#[rust_name = "add_years"]
fn addYears(self: &QDateTime, nyears: i32) -> QDateTime;
/// Returns the date part of the datetime.
fn date(self: &QDateTime) -> QDate;
/// Returns the number of days from this datetime to the other datetime.
/// The number of days is counted as the number of times midnight is reached between this datetime to the other datetime.
/// This means that a 10 minute difference from 23:55 to 0:05 the next day counts as one day.
#[rust_name = "days_to"]
fn daysTo(self: &QDateTime, other: &QDateTime) -> qint64;
/// Returns if this datetime falls in Daylight-Saving Time.
#[rust_name = "is_daylight_time"]
fn isDaylightTime(self: &QDateTime) -> bool;
/// Returns true if both the date and the time are null; otherwise returns false. A null datetime is invalid.
#[rust_name = "is_null"]
fn isNull(self: &QDateTime) -> bool;
/// Returns true if both the date and the time are valid and they are valid in the current Qt::TimeSpec, otherwise returns false.
#[rust_name = "is_valid"]
fn isValid(self: &QDateTime) -> bool;
/// Returns this date-time's Offset From UTC in seconds.
#[rust_name = "offset_from_utc"]
fn offsetFromUtc(self: &QDateTime) -> i32;
/// Returns the number of milliseconds from this datetime to the other datetime.
/// If the other datetime is earlier than this datetime, the value returned is negative.
#[rust_name = "msecs_to"]
fn msecsTo(self: &QDateTime, other: &QDateTime) -> qint64;
/// Returns the number of seconds from this datetime to the other datetime.
/// If the other datetime is earlier than this datetime, the value returned is negative.
#[rust_name = "secs_to"]
fn secsTo(self: &QDateTime, other: &QDateTime) -> qint64;
/// Sets the date and time given the number of milliseconds msecs that have passed since 1970-01-01T00:00:00.000,
/// Coordinated Universal Time (Qt::UTC). On systems that do not support time zones this function will behave as if local time were Qt::UTC.
#[rust_name = "set_msecs_since_epoch"]
fn setMSecsSinceEpoch(self: &mut QDateTime, msecs: qint64);
/// Sets the timeSpec() to Qt::OffsetFromUTC and the offset to offsetSeconds.
///
/// Note this method is only available with Qt < 6.8
#[cfg(not(cxxqt_qt_version_at_least_6_8))]
#[rust_name = "set_offset_from_utc"]
fn setOffsetFromUtc(self: &mut QDateTime, offset_seconds: i32);
/// Sets the date and time given the number of seconds secs that have passed since 1970-01-01T00:00:00.000,
/// Coordinated Universal Time (Qt::UTC). On systems that do not support time zones this function will behave as if local time were Qt::UTC.
#[rust_name = "set_secs_since_epoch"]
fn setSecsSinceEpoch(self: &mut QDateTime, secs: qint64);
/// Sets the time specification used in this datetime to spec. The datetime will refer to a different point in time.
///
/// Note this method is only available with Qt < 6.8
#[cfg(not(cxxqt_qt_version_at_least_6_8))]
#[rust_name = "set_time_spec"]
fn setTimeSpec(self: &mut QDateTime, spec: TimeSpec);
/// Returns the time part of the datetime.
fn time(self: &QDateTime) -> QTime;
/// Returns the time specification of the datetime.
#[rust_name = "time_spec"]
fn timeSpec(self: &QDateTime) -> TimeSpec;
/// Returns the Time Zone Abbreviation for this datetime.
#[rust_name = "time_zone_abbreviation"]
fn timeZoneAbbreviation(self: &QDateTime) -> QString;
/// Returns a datetime containing the date and time information in this datetime, but specified using the Qt::LocalTime definition.
#[rust_name = "to_local_time"]
fn toLocalTime(self: &QDateTime) -> QDateTime;
/// Returns the datetime as the number of milliseconds that have passed since 1970-01-01T00:00:00.000, Coordinated Universal Time (Qt::UTC).
#[rust_name = "to_msecs_since_epoch"]
fn toMSecsSinceEpoch(self: &QDateTime) -> qint64;
/// Returns a copy of this datetime converted to a spec of Qt::OffsetFromUTC with the given offsetSeconds.
#[rust_name = "to_offset_from_utc"]
fn toOffsetFromUtc(self: &QDateTime, offset_seconds: i32) -> QDateTime;
/// Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00.000, Coordinated Universal Time (Qt::UTC).
#[rust_name = "to_secs_since_epoch"]
fn toSecsSinceEpoch(self: &QDateTime) -> qint64;
/// Returns the time as a string. The format parameter determines the format of the string.
#[rust_name = "format_enum"]
fn toString(self: &QDateTime, format: DateFormat) -> QString;
/// Returns a copy of this datetime converted to the given time spec.
///
/// Note this method is only available with Qt < 6.8
#[cfg(not(cxxqt_qt_version_at_least_6_8))]
#[rust_name = "to_time_spec"]
fn toTimeSpec(self: &QDateTime, spec: TimeSpec) -> QDateTime;
/// Returns a copy of this datetime converted to the given timeZone
#[rust_name = "to_time_zone"]
fn toTimeZone(self: &QDateTime, timeZone: &QTimeZone) -> QDateTime;
/// Returns a datetime containing the date and time information in this datetime, but specified using the Qt::UTC definition.
#[rust_name = "to_utc"]
fn toUTC(self: &QDateTime) -> QDateTime;
}
#[namespace = "rust::cxxqtlib1"]
unsafe extern "C++" {
#[doc(hidden)]
#[rust_name = "qdatetime_current_date_time"]
fn qdatetimeCurrentDateTime() -> QDateTime;
#[doc(hidden)]
#[rust_name = "qdatetime_current_date_time_utc"]
fn qdatetimeCurrentDateTimeUtc() -> QDateTime;
#[doc(hidden)]
#[rust_name = "qdatetime_current_msecs_since_epoch"]
fn qdatetimeCurrentMSecsSinceEpoch() -> qint64;
#[doc(hidden)]
#[rust_name = "qdatetime_current_secs_since_epoch"]
fn qdatetimeCurrentSecsSinceEpoch() -> qint64;
#[doc(hidden)]
#[rust_name = "qdatetime_from_msecs_since_epoch"]
fn qdatetimeFromMSecsSinceEpoch(msecs: qint64, time_zone: &QTimeZone) -> QDateTime;
#[doc(hidden)]
#[rust_name = "qdatetime_from_secs_since_epoch"]
fn qdatetimeFromSecsSinceEpoch(secs: qint64, time_zone: &QTimeZone) -> QDateTime;
// Note that Qt 5 takes const-ref and Qt 6 takes by-value
// for QDateTime::setDate and QDateTime::setTime
//
// We want by-value, as that is Rust-idiomatic, so for Qt 5 we create a proxy
#[doc(hidden)]
#[rust_name = "qdatetime_set_date"]
fn qdatetimeSetDate(datetime: &mut QDateTime, date: QDate);
#[doc(hidden)]
#[rust_name = "qdatetime_set_time"]
fn qdatetimeSetTime(datetime: &mut QDateTime, time: QTime);
#[doc(hidden)]
#[rust_name = "qdatetime_time_zone"]
fn qdatetimeTimeZone(datetime: &QDateTime) -> UniquePtr<QTimeZone>;
#[rust_name = "qdatetime_settimezone"]
fn qdatetimeSetTimeZone(datetime: &mut QDateTime, time_zone: &QTimeZone);
#[doc(hidden)]
#[rust_name = "qdatetime_from_string"]
fn qdatetimeFromQString(string: &QString, format: DateFormat) -> QDateTime;
}
#[namespace = "rust::cxxqtlib1"]
unsafe extern "C++" {
include!("cxx-qt-lib/common.h");
#[doc(hidden)]
#[rust_name = "qdatetime_drop"]
fn drop(datetime: &mut QDateTime);
#[doc(hidden)]
#[rust_name = "qdatetime_init_default"]
fn construct() -> QDateTime;
#[doc(hidden)]
#[rust_name = "qdatetime_init_from_date_and_time_time_zone"]
fn construct(date: &QDate, time: &QTime, time_zone: &QTimeZone) -> QDateTime;
#[cfg(not(cxxqt_qt_version_at_least_6_8))]
#[doc(hidden)]
#[rust_name = "qdatetime_init_from_date_and_time_time_spec"]
fn construct(
date: &QDate,
time: &QTime,
time_spec: TimeSpec,
offset_seconds: i32,
) -> QDateTime;
#[doc(hidden)]
#[rust_name = "qdatetime_init_from_qdatetime"]
fn construct(datetime: &QDateTime) -> QDateTime;
#[doc(hidden)]
#[rust_name = "qdatetime_eq"]
fn operatorEq(a: &QDateTime, b: &QDateTime) -> bool;
#[doc(hidden)]
#[rust_name = "qdatetime_cmp"]
fn operatorCmp(a: &QDateTime, b: &QDateTime) -> i8;
#[doc(hidden)]
#[rust_name = "qdatetime_to_debug_qstring"]
fn toDebugQString(value: &QDateTime) -> QString;
}
}
/// The QDateTime class provides date and time functions.
#[repr(C)]
pub struct QDateTime {
_space: MaybeUninit<usize>,
}
impl QDateTime {
/// Sets the time zone used in this datetime to toZone. The datetime will refer to a different point in time.
pub fn set_time_zone(&mut self, time_zone: &ffi::QTimeZone) {
ffi::qdatetime_settimezone(self, time_zone)
}
/// Returns the current datetime, as reported by the system clock, in the local time zone.
pub fn current_date_time() -> Self {
ffi::qdatetime_current_date_time()
}
/// Returns the current datetime, as reported by the system clock, in UTC.
pub fn current_date_time_utc() -> Self {
ffi::qdatetime_current_date_time_utc()
}
/// Returns the number of milliseconds since 1970-01-01T00:00:00 Universal Coordinated Time.
/// This number is like the POSIX time_t variable, but expressed in milliseconds instead.
pub fn current_msecs_since_epoch() -> ffi::qint64 {
ffi::qdatetime_current_msecs_since_epoch()
}
/// Returns the number of seconds since 1970-01-01T00:00:00 Universal Coordinated Time.
pub fn current_secs_since_epoch() -> ffi::qint64 {
ffi::qdatetime_current_secs_since_epoch()
}
/// Construct a Rust QDateTime from a given QDate, QTime, and QTimeZone
pub fn from_date_and_time_time_zone(
date: &QDate,
time: &QTime,
time_zone: &ffi::QTimeZone,
) -> Self {
ffi::qdatetime_init_from_date_and_time_time_zone(date, time, time_zone)
}
/// Construct a Rust QDateTime from a given QDate, QTime, Qt::TimeSpec, and offset
///
/// Note this method is only available with Qt < 6.8
#[cfg(not(cxxqt_qt_version_at_least_6_8))]
pub fn from_date_and_time_time_spec(
date: &QDate,
time: &QTime,
time_spec: ffi::TimeSpec,
offset_seconds: i32,
) -> Self {
ffi::qdatetime_init_from_date_and_time_time_spec(date, time, time_spec, offset_seconds)
}
/// Returns a datetime whose date and time are the number of milliseconds msecs that have passed since 1970-01-01T00:00:00.000,
/// Coordinated Universal Time (Qt::UTC) and with the given timeZone.
pub fn from_msecs_since_epoch(msecs: ffi::qint64, time_zone: &ffi::QTimeZone) -> Self {
ffi::qdatetime_from_msecs_since_epoch(msecs, time_zone)
}
/// Returns a datetime whose date and time are the number of seconds secs that have passed since 1970-01-01T00:00:00.000,
/// Coordinated Universal Time (Qt::UTC) and converted to the given spec.
pub fn from_secs_since_epoch(secs: ffi::qint64, time_zone: &ffi::QTimeZone) -> Self {
ffi::qdatetime_from_secs_since_epoch(secs, time_zone)
}
/// Returns the datetime represented in the string as a QDateTime using the format given, or None if this is not possible.
pub fn from_string(string: &ffi::QString, format: ffi::DateFormat) -> Option<Self> {
let date = ffi::qdatetime_from_string(string, format);
if date.is_valid() {
Some(date)
} else {
None
}
}
/// Sets the date part of this datetime to date. If no time is set yet, it is set to midnight.
/// If date is invalid, this QDateTime becomes invalid.
pub fn set_date(&mut self, date: QDate) {
ffi::qdatetime_set_date(self, date);
}
/// Sets the time part of this datetime to time. If time is not valid, this function sets it to midnight.
/// Therefore, it's possible to clear any set time in a QDateTime by setting it to a default QTime.
pub fn set_time(&mut self, time: QTime) {
ffi::qdatetime_set_time(self, time);
}
/// Returns the time zone of the datetime.
pub fn time_zone(&self) -> cxx::UniquePtr<ffi::QTimeZone> {
ffi::qdatetime_time_zone(self)
}
}
impl Clone for QDateTime {
/// Constructs a copy of the other datetime.
fn clone(&self) -> Self {
ffi::qdatetime_init_from_qdatetime(self)
}
}
impl Default for QDateTime {
/// Construct a default null QDateTime
fn default() -> Self {
ffi::qdatetime_init_default()
}
}
impl PartialEq for QDateTime {
fn eq(&self, other: &Self) -> bool {
ffi::qdatetime_eq(self, other)
}
}
impl Eq for QDateTime {}
impl PartialOrd for QDateTime {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for QDateTime {
fn cmp(&self, other: &Self) -> Ordering {
ffi::qdatetime_cmp(self, other).cmp(&0)
}
}
impl fmt::Display for QDateTime {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.format_enum(ffi::DateFormat::TextDate))
}
}
impl fmt::Debug for QDateTime {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", ffi::qdatetime_to_debug_qstring(self))
}
}
impl Drop for QDateTime {
/// Destroys the datetime.
fn drop(&mut self) {
ffi::qdatetime_drop(self);
}
}
#[cfg(feature = "chrono")]
use chrono::Offset;
#[cfg(feature = "chrono")]
impl<Tz: chrono::TimeZone> TryFrom<chrono::DateTime<Tz>> for QDateTime {
type Error = &'static str;
fn try_from(value: chrono::DateTime<Tz>) -> Result<Self, Self::Error> {
let tz = crate::QTimeZone::from_offset_seconds(value.offset().fix().local_minus_utc());
Ok(QDateTime::from_date_and_time_time_zone(
&QDate::from(value.date_naive()),
&QTime::try_from(value.time())?,
tz.as_ref().ok_or("Could not construct timezone")?,
))
}
}
#[cfg(feature = "chrono")]
impl TryFrom<QDateTime> for chrono::DateTime<chrono::FixedOffset> {
type Error = &'static str;
fn try_from(value: QDateTime) -> Result<Self, Self::Error> {
let timezone_east = chrono::FixedOffset::east_opt(value.offset_from_utc())
.expect("out-of-bound offset secs");
let value_utc = value.to_utc();
let naivedatetime_east = chrono::NaiveDate::try_from(value_utc.date())?
.and_time(chrono::NaiveTime::try_from(value_utc.time())?);
Ok(
chrono::DateTime::<chrono::FixedOffset>::from_naive_utc_and_offset(
naivedatetime_east,
timezone_east,
),
)
}
}
#[cfg(feature = "chrono")]
impl TryFrom<QDateTime> for chrono::DateTime<chrono::Utc> {
type Error = &'static str;
fn try_from(value: QDateTime) -> Result<Self, Self::Error> {
let value_utc = value.to_utc();
let naivedatetime_utc = chrono::NaiveDate::try_from(value_utc.date())?
.and_time(chrono::NaiveTime::try_from(value_utc.time())?);
Ok(chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
naivedatetime_utc,
chrono::Utc,
))
}
}
#[cfg(feature = "time")]
impl From<time::OffsetDateTime> for QDateTime {
fn from(value: time::OffsetDateTime) -> Self {
let tz = crate::QTimeZone::from_offset_seconds(value.offset().whole_seconds());
QDateTime::from_date_and_time_time_zone(
&QDate::from(value.date()),
&QTime::from(value.time()),
tz.as_ref().expect("Could not construct timezone"),
)
}
}
#[cfg(feature = "time")]
impl From<time::PrimitiveDateTime> for QDateTime {
fn from(value: time::PrimitiveDateTime) -> Self {
let tz = crate::QTimeZone::utc();
QDateTime::from_date_and_time_time_zone(
&QDate::from(value.date()),
&QTime::from(value.time()),
tz.as_ref().expect("Could not construct timezone"),
)
}
}
#[cfg(feature = "time")]
impl TryFrom<QDateTime> for time::OffsetDateTime {
type Error = time::error::ComponentRange;
fn try_from(value: QDateTime) -> Result<Self, Self::Error> {
Ok(time::Date::try_from(value.date())?
.with_time(time::Time::try_from(value.time())?)
.assume_offset(time::UtcOffset::from_whole_seconds(
value.offset_from_utc(),
)?))
}
}
#[cfg(feature = "time")]
impl TryFrom<QDateTime> for time::PrimitiveDateTime {
type Error = time::error::ComponentRange;
fn try_from(value: QDateTime) -> Result<Self, Self::Error> {
let value_utc = value.to_utc();
Ok(time::Date::try_from(value_utc.date())?
.with_time(time::Time::try_from(value_utc.time())?))
}
}
// Safety:
//
// Static checks on the C++ side to ensure the size is the same.
unsafe impl ExternType for QDateTime {
type Id = type_id!("QDateTime");
type Kind = cxx::kind::Trivial;
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_ordering() {
let qdatetime_a = QDateTime::from_date_and_time_time_zone(
&QDate::new(2023, 1, 1),
&QTime::new(1, 1, 1, 1),
&ffi::QTimeZone::utc(),
);
let qdatetime_b = QDateTime::from_date_and_time_time_zone(
&QDate::new(2023, 2, 2),
&QTime::new(2, 2, 2, 2),
&ffi::QTimeZone::utc(),
);
assert!(qdatetime_a < qdatetime_b);
assert_eq!(qdatetime_a.cmp(&qdatetime_b), Ordering::Less);
assert_eq!(qdatetime_b.cmp(&qdatetime_a), Ordering::Greater);
assert_eq!(qdatetime_a.cmp(&qdatetime_a), Ordering::Equal);
}
#[cfg(feature = "serde")]
#[test]
fn qdatetime_serde() {
let qdatetime = QDateTime::from_date_and_time_time_zone(
&QDate::new(2023, 1, 1),
&QTime::new(1, 1, 1, 1),
&ffi::QTimeZone::utc(),
);
assert_eq!(crate::serde_impl::roundtrip(&qdatetime), qdatetime);
}
}
#[cfg(test)]
#[cfg(feature = "chrono")]
mod test_chrono {
use super::*;
#[test]
fn qdatetime_from_chrono() {
let datetime_east = {
let timezone_east = chrono::FixedOffset::east_opt(60 * 60).unwrap();
let naivedatetime_east = chrono::NaiveDate::from_ymd_opt(2023, 1, 1)
.unwrap()
.and_hms_milli_opt(1, 2, 3, 4)
.unwrap();
chrono::DateTime::<chrono::FixedOffset>::from_naive_utc_and_offset(
naivedatetime_east,
timezone_east,
)
};
let qdatetime = QDateTime::from_date_and_time_time_zone(
&QDate::new(2023, 1, 1),
// Chrono adds the offset to the given time, so add the offset here to match Chrono
&QTime::new(1 + 1 /* plus the offset */, 2, 3, 4),
&ffi::QTimeZone::from_offset_seconds(60 * 60),
);
assert_eq!(QDateTime::try_from(datetime_east).unwrap(), qdatetime);
}
#[test]
fn qdatetime_to_chrono_fixed_offset() {
let datetime_east = {
let timezone_east = chrono::FixedOffset::east_opt(60 * 60).unwrap();
let naivedatetime_east = chrono::NaiveDate::from_ymd_opt(2023, 1, 1)
.unwrap()
// Chrono adds the offset to the given time, so minus the offset here to match Qt
.and_hms_milli_opt(1 - 1 /* minus the offset */, 2, 3, 4)
.unwrap();
chrono::DateTime::<chrono::FixedOffset>::from_naive_utc_and_offset(
naivedatetime_east,
timezone_east,
)
};
let qdatetime = QDateTime::from_date_and_time_time_zone(
&QDate::new(2023, 1, 1),
&QTime::new(1, 2, 3, 4),
&ffi::QTimeZone::from_offset_seconds(60 * 60),
);
assert_eq!(
chrono::DateTime::<chrono::FixedOffset>::try_from(qdatetime).unwrap(),
datetime_east
);
}
#[test]
fn qdatetime_to_chrono_utc() {
let datetime_utc = {
let naivedatetime_utc = chrono::NaiveDate::from_ymd_opt(2023, 1, 1)
.unwrap()
.and_hms_milli_opt(1, 2, 3, 4)
.unwrap();
chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
naivedatetime_utc,
chrono::Utc,
)
};
let qdatetime = QDateTime::from_date_and_time_time_zone(
&QDate::new(2023, 1, 1),
&QTime::new(1, 2, 3, 4),
&ffi::QTimeZone::utc(),
);
assert_eq!(
chrono::DateTime::<chrono::Utc>::try_from(qdatetime).unwrap(),
datetime_utc
);
}
#[test]
fn qdatetime_to_chrono_utc_with_offset() {
let datetime_utc = {
let naivedatetime_utc = chrono::NaiveDate::from_ymd_opt(2023, 1, 1)
.unwrap()
.and_hms_milli_opt(0, 2, 3, 4)
.unwrap();
chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
naivedatetime_utc,
chrono::Utc,
)
};
let qdatetime = QDateTime::from_date_and_time_time_zone(
&QDate::new(2023, 1, 1),
&QTime::new(1, 2, 3, 4),
// Should cause one hour offset when in chrono::DateTime
&ffi::QTimeZone::from_offset_seconds(60 * 60),
);
assert_eq!(
chrono::DateTime::<chrono::Utc>::try_from(qdatetime).unwrap(),
datetime_utc
);
}
}
#[cfg(test)]
#[cfg(feature = "time")]
mod test_time {
use super::*;
#[test]
fn qdatetime_to_time_offsetdatetime() {
let time_offsetdatetime = time::Date::from_calendar_date(2023, time::Month::January, 1)
.unwrap()
.with_hms_milli(1, 2, 3, 4)
.unwrap()
.assume_offset(time::UtcOffset::from_whole_seconds(60 * 60).unwrap());
let qdatetime = QDateTime::from_date_and_time_time_zone(
&QDate::new(2023, 1, 1),
&QTime::new(1, 2, 3, 4),
&ffi::QTimeZone::from_offset_seconds(60 * 60),
);
assert_eq!(
time::OffsetDateTime::try_from(qdatetime).unwrap(),
time_offsetdatetime
);
}
#[test]
fn qdatetime_to_time_primitivedatetime() {
let time_offsetdatetime = time::Date::from_calendar_date(2023, time::Month::January, 1)
.unwrap()
.with_hms_milli(1, 2, 3, 4)
.unwrap();
let qdatetime = QDateTime::from_date_and_time_time_zone(
&QDate::new(2023, 1, 1),
&QTime::new(1, 2, 3, 4),
&ffi::QTimeZone::utc(),
);
assert_eq!(
time::PrimitiveDateTime::try_from(qdatetime).unwrap(),
time_offsetdatetime
);
}
#[test]
fn qdatetime_from_time_offsetdatetime() {
let time_offsetdatetime = time::Date::from_calendar_date(2023, time::Month::January, 1)
.unwrap()
.with_hms_milli(1, 2, 3, 4)
.unwrap()
.assume_offset(time::UtcOffset::from_whole_seconds(60 * 60).unwrap());
let qdatetime = QDateTime::from_date_and_time_time_zone(
&QDate::new(2023, 1, 1),
&QTime::new(1, 2, 3, 4),
&ffi::QTimeZone::from_offset_seconds(60 * 60),
);
assert_eq!(QDateTime::from(time_offsetdatetime), qdatetime);
}
#[test]
fn qdatetime_from_time_primitivedatetime() {
let time_offsetdatetime = time::Date::from_calendar_date(2023, time::Month::January, 1)
.unwrap()
.with_hms_milli(1, 2, 3, 4)
.unwrap();
let qdatetime = QDateTime::from_date_and_time_time_zone(
&QDate::new(2023, 1, 1),
&QTime::new(1, 2, 3, 4),
&ffi::QTimeZone::utc(),
);
assert_eq!(QDateTime::from(time_offsetdatetime), qdatetime);
}
}