Blog

Displaying Dates in Ruby Using the Sinatra Ruby Framework
Posted on August 7, 2015 in Ruby, Sinatra by Matt Jennings

/server.rb File

require "sinatra"
require "date"

get "/" do
  # Use "Time.new" to get the current date and time
  time = Time.new
  time.month

  # Get month name
  @month = Date::MONTHNAMES[Date.today.month]

  # Get current day of month
  @day_of_month = time.day

  # Get current year
  @year = time.year

  # Get current hour
  @hour = time.hour

  # Set variable a starting value of "AM"
  @am_pm = "AM"

  if @hour > 12
    @hour = (@hour - 12).to_s
    # Reset variable to "PM"
    @am_pm = "PM"
  end

  # Get current minutes
  @minutes = time.min

  if @minutes < 10
    @minutes = "0" + @minutes.to_s
  end

  erb :index
end

/views/index.erb

<!doctype>
<html>
<head>
    <meta charset="utf-8" />
    <title>Date and Time</title>
    <link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>
<body>

    <div id="wrapper">

        <div id="date-time-heading">
          The current time and date:
        </div>

        <div id="date-time-value">
            <%= @month.to_s + " " + @day_of_month.to_s + ", " + @year.to_s %><br />
            <%= @hour.to_s + ":" + @minutes.to_s + " " + @am_pm %>
        </div>

    </div>

</body>
</html>

/publics/css/styles.css

body {
    padding: 0;
    margin: 0;
    font-family: Helvetica, Arial, sans-serif;
}

#wrapper {
    width: 920px;
    padding: 20px;
    margin: 0 auto;
}

#date-time-heading {
    width: 200px;
    border: 1px solid #000;
    margin: 0 auto;
    text-align: center;
    padding: 15px;
}

#date-time-value {
    width: 450px;
    border: 1px solid #000;
    margin: 20px auto 0;
    font-size: 28px;
    font-weight: bold;
    padding: 15px;
    text-align: center;
}

Leave a Reply

To Top ↑