Learn and Learn

Learn And Learn - great place for tutorials, references and how-to

Ruby – Set Various Date Object / Formats – strptime Method with Examples

The difference between _strptime and strptime is that the earlier gives somewhat fewer details about the given representation of date than the later. To create a new strptime date object in Ruby language, use Date.strptime() method.

strptime() Method in Ruby

strptime() method exists in Standard Date Library of Ruby. The purpose of this method is to described the given representation of date 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:

 

Parameter of strptime() Method in Ruby

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

 

Return Value of strptime()

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

 

Set Date Format with strptime() Method in Ruby


Output
2015-05-05

 

Various Date Formats of strptime() Method in Ruby with Explanation


Output
2015-05-05

 

strptime() Date Method in Ruby


Output
2015-02-24

NOTE: In the above code 055 represents the 55th day of the year 2015 and %j (iso 8601 format) shows the extended ordinal date.

 


Output
2015-05-05

 

Use of wyear and wday in strptime() Date Method in Ruby


Output
2015-03-07

NOTE: In the above code W10 and 6 represents the 10th week and 6th day of that particular week of the year 2015 and alphabets with % sign (iso 8601 format) shows the extended week date.

 

strptime() Format Directives:

Following are some of the mostly used iso 8601 format directives in strptime():

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

 

Loading...
LearnAndLearn.com © 2018 - All rights reserved