Automatically exported from code.google.com/p/planningalerts
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

80 lines
2.1 KiB

  1. package DateTime::Format::DateParse;
  2. # Copyright (C) 2005-6 Joshua Hoblitt
  3. #
  4. # $Id: DateParse.pm 3517 2006-09-17 23:10:10Z jhoblitt $
  5. use strict;
  6. use vars qw($VERSION);
  7. $VERSION = '0.04';
  8. use DateTime;
  9. use DateTime::TimeZone;
  10. use Date::Parse qw( strptime );
  11. use Time::Zone qw( tz_offset );
  12. sub parse_datetime {
  13. my ($class, $date, $zone) = @_;
  14. # str2time() calls strptime() internally so it's more efficent to use
  15. # strptime() directly. However, the extra validation done by using
  16. # DateTime->new() instad of DateTime->from_epoch() may make it into a net
  17. # loss. In the end, it turns out that strptime()'s offset information is
  18. # needed anyways.
  19. my @t = strptime( $date, $zone );
  20. return undef unless @t;
  21. my ($ss, $mm, $hh, $day, $month, $year, $offset) = @t;
  22. my %p;
  23. if ( $ss ) {
  24. my $fraction = $ss - int( $ss );
  25. $p{ nanosecond } = $fraction * 1e9 if $fraction;
  26. $p{ second } = int $ss;
  27. }
  28. $p{ minute } = $mm if $mm;
  29. $p{ hour } = $hh if $hh;
  30. $p{ day } = $day if $day;
  31. $p{ month } = $month + 1 if $month;
  32. $p{ year } = $year ? $year + 1900 : DateTime->now->year;
  33. # unless there is an explict ZONE, Date::Parse seems to parse date only
  34. # formats, eg. "1995-01-24", as being in the 'local' timezone.
  35. unless ( defined $zone || defined $offset ) {
  36. return DateTime->new(
  37. %p,
  38. time_zone => 'local',
  39. );
  40. }
  41. if ( $zone ) {
  42. if ( DateTime::TimeZone->is_valid_name( $zone ) ) {
  43. return DateTime->new(
  44. %p,
  45. time_zone => $zone,
  46. );
  47. } else {
  48. # attempt to convert Time::Zone tz's into an offset
  49. return DateTime->new(
  50. %p,
  51. time_zone =>
  52. # not an Olson timezone, no DST info
  53. DateTime::TimeZone::offset_as_string( tz_offset( $zone ) ),
  54. );
  55. }
  56. }
  57. return DateTime->new(
  58. %p,
  59. time_zone =>
  60. # not an Olson timezone, no DST info
  61. DateTime::TimeZone::offset_as_string( $offset ),
  62. );
  63. }
  64. 1;
  65. __END__