Ruby – _strptime() Function – Examples & Explanation

_strptime() method exists in the standard library of Ruby programming. The _strptime() method describes the given representation of date and time and with the given templates and returns the described elements in Ruby programming language. To find out the parse of the any given date in Ruby, use _strptime() method.

_strptime() Method in Ruby

date._strptime() method exists in Standard Date Library of Ruby. The purpose of this method is to describes the given representation of date and time with the given templates and returns the described elements. The _strptime() is not supported for the indicated flags and width.

 

Syntax of the _strptime() Method in Ruby

In date, the syntax of _strptime() method is

Date._strptime( x )

 

Parameters of _strptime() Method in Ruby

x – Where x is any valid date object. This parameter is required.
Note: If the x parameter is not a date object, _strptime() method will return an error.

 

Return Value of _strptime()

_strptime() method will return the given representation of date and time with the given templates and returns the described elements.

 

Explain Date with _strptime Method Example 1

# import date library
require ‘date’

date = Date._strptime('2011-12-23', '%Y-%m-%d')
puts date

Output
{:year=>2011, :mon=>12, :mday=>23}

 

Explain Date with _strptime Method Example 2

# import date library
require 'date'
date = Date._strptime('23-12-2011', '%d-%m-%Y')
puts date

Output:
{:mday=>23, :mon=>12, :year=>2011}

 

Explain Date and Time with _strptime Method Example 3

# import date library
require ‘date’
date = DateTime._strptime('09/18/2012 7:00', '%m/%d/%Y %H:%M')
puts date

Output
{:mon=>9, :mday=>18, :year=>2012, :hour=>7, :min=>0}

 

_strptime() Format Directives

Following are some of the mostly used format directives in _strptime():

# Format Description
1 %A The uppercase (A) means the full week day name like “MONDAY”
2 %a The lowercase (a) means the abbreviated name for a week day like “Mon”
3 %B The uppercase (B) means the full month name like “MARCH”
4 %b The lowercase (b) means the abbreviated name for a month like “Mar”
5 %D It means date like m/d/y.
6 %d It means any day of the year like (01 to 31)
7 %M It means clock time like (00 to 59)
8 %m It means the number of a month like (01 to 12)
9 %S It means second of the minutes like (00 to 59)
10 %s It means Number of seconds like since 2010-01-01 00:00:00 GMT.
11 %Y It means the year of the century
12 %y It means year as (2009 become 09)