Class: Time

Inherits:
Object show all
Defined in:
lib/sup/util.rb

Constant Summary collapse

TO_NICE_S_MAX_LEN =

e.g. “Yest.10am”

9

Instance Method Summary collapse

Instance Method Details

#is_the_day_before?(other) ⇒ Boolean

Returns:

  • (Boolean)


538
539
540
# File 'lib/sup/util.rb', line 538

def is_the_day_before? other
  other.midnight - midnight <=  24 * 60 * 60 + 1
end

#is_the_same_day?(other) ⇒ Boolean

Returns:

  • (Boolean)


534
535
536
# File 'lib/sup/util.rb', line 534

def is_the_same_day? other
  (midnight - other.midnight).abs < 1
end

#midnightObject

within a second



530
531
532
# File 'lib/sup/util.rb', line 530

def midnight # within a second
  self - (hour * 60 * 60) - (min * 60) - sec
end

#nearest_hourObject



522
523
524
525
526
527
528
# File 'lib/sup/util.rb', line 522

def nearest_hour
  if min < 30
    self
  else
    self + (60 - min) * 60
  end
end

#to_indexable_sObject



518
519
520
# File 'lib/sup/util.rb', line 518

def to_indexable_s
  sprintf "%012d", self
end

#to_nice_distance_s(from = Time.now) ⇒ Object



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
# File 'lib/sup/util.rb', line 542

def to_nice_distance_s from=Time.now
  later_than = (self < from)
  diff = (self.to_i - from.to_i).abs.to_f
  text = 
    [ ["second", 60],
      ["minute", 60],
      ["hour", 24],
      ["day", 7],
      ["week", 4.345], # heh heh
      ["month", 12],
      ["year", nil],
    ].argfind do |unit, size|
      if diff.round <= 1
        "one #{unit}"
      elsif size.nil? || diff.round < size
        "#{diff.round} #{unit}s"
      else
        diff /= size.to_f
        false
      end
    end
  if later_than
    text + " ago"
  else
    "in " + text
  end  
end

#to_nice_s(from = Time.now) ⇒ Object



571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# File 'lib/sup/util.rb', line 571

def to_nice_s from=Time.now
  if year != from.year
    strftime "%b %Y"
  elsif month != from.month
    strftime "%b %e"
  else
    if is_the_same_day? from
      strftime("%l:%M%p").downcase # emulate %P (missing on ruby 1.8 darwin)
    elsif is_the_day_before? from
      "Yest."  + nearest_hour.strftime("%l%p").downcase # emulate %P
    else
      strftime "%b %e"
    end
  end
end