[Rails] Mask an image using ImageMagick, Paperclip and S3

A project I’m currently working on requires image masking. I had already developed the site with plans to deploy to Heroku using Paperclip for image attachments using Amazon S3 for storage (you can read how I set that up here). I scoured the web for existing tutorials and documentation but found little that was relevant to my situation. My first inclination was to write a post-process method – grab the image, mask it and write it back to S3 which proved to be a dead-end (you can see the problem I ran into here – granted it’s possible you could still go that route). After a bit of Googling I ended up using a processor. Here’s what I did (I must confess the “boilerplate” code for the processor was some I found, unfortunately I did not keep the link – if you recognize it please let me know!):

In my model:

  has_attached_file :image,
  :styles =>{
    :main_feature => {:geometry => "1020x470", :processors => [:masker] },
    :large => "1020x470",
    :event_page => "460x212", 
    :top_feature => "345x159",
    :smallest => "229x131"#,
  },
  :storage => :s3,
  :s3_credentials => "#{Rails.root}/config/s3.yml",
  :path => ":attachment/:id/:style.:extension",
  :url => "/:id/:style/:basename.:extension",
  :bucket => "yo-bucket-name"

Note line 3, where I’ve added a processor called “masker”. I created a folder called ‘paperclip_processors’ inside my lib directory and created masker.rb. In that same folder I included the png of my mask (mine is simply called mask.png). I’m using an alpha mask. In masker.rb I placed the following code:

module Paperclip
  class Masker < Processor
    def initialize file, options = {}, attachment = nil
      super
      @format = File.extname(@file.path)
      @basename = File.basename(@file.path, @format)
    end

     def make  
          
      src = @file
      dst = Tempfile.new([@basename, @format])
      dst.binmode

      begin
        parameters = []
        
        parameters << ':source'
        parameters << ':mask'
        parameters << '-alpha'
        parameters << 'on'
        parameters << '-compose'
        parameters << 'CopyOpacity'
        parameters << '-composite'
        parameters << ':dest'

        parameters = parameters.flatten.compact.join(" ").strip.squeeze(" ")

        mask_path = File.expand_path('lib/paperclip_processors/mask.png')
        success = Paperclip.run("convert", parameters, :source => "#{File.expand_path(src.path)}[0]", :mask => "#{mask_path}[0]", :dest => File.expand_path(dst.path))
      


       rescue PaperclipCommandLineError => e
         raise PaperclipError, "There was an error during the mask for #{@basename}" if @whiny
       end

       dst
     end

  end
end

Lines 18-25 show the arguments we’ll be using to interface with ImageMagick (the documentation for this is found here). Basically we’re inputting the source and mask, turning the alpha flag on, using the compose method with CopyOpacity to copy the opacity of the mask to the final composite (masked) image and finally the destination. Now when an image is added to my model, a new image is sized and created – best of all, it works on Heroku!

Automagically: Easy Splash Screen (Default.png)

In my recent post about reducing load time for iOS apps, I discussed the importance of a proper Default.png. In the past I’ve made my Default.png “splash screen” image manually from mock ups and screenshots from the simulator — it can be very tedious with mixed results.

There is another way.

Before I show you, you need to know something — it uses a private API function. What does that mean? You need to remove this code before you submit your app to the App Store or it will be rejected. Private APIs are functions not to be used by anyone but Apple. So without further ado:

[[UIApplication sharedApplication] _writeApplicationDefaultPNGSnapshot];

That’s it. You should put this code somewhere in your viewDidLoad function before you load all (but after you load some) of your UI elements. You’ll have to be the judge of the appropriate timing. Once this function is run, it’ll store a PNG screenshot of your application in the following location:

Library/Application Support/iPhone Simulator/VERSION/UDID/Caches/BUNDLEIDENTIFIER/AppSnapshots/

QUICK! Get the screenshot and get outta there — then remove that function.

Load it Faster: Speed Up Your iOS App Loading Time

I’m always thinking about how to make my apps run and load faster. It’s incredibly important, especially to your users. Earlier today I ran across a Twitter conversation (http://twitter.com/flyosity/status/239044820394471424) between a few guys I consider to be top notch: Sam Soffes, Jake Marsh and Mike Rundle. They were discussing best practices for getting your app loading speed down.

There’s a great article by Brent Simmons in which he discusses his methods for making Glassboard 2.2 load faster, it’s available here:
http://inessential.com/2012/08/23/an_iphone_app_startup_performance_techni

Mike also pointed out Sam’s code from Cheddar:
https://github.com/nothingmagical/cheddar-ios/blob/master/Classes/CDIAppDelegate.m#L68

In his didFinishLaunching method, he performs only the most essential tasks and puts everything else in an async queue to run in the background without blocking the main thread. This frees the app up to get the UI and other elements rolling.

On top of this optimization you can do a few things to make your app APPEAR to load faster, namely, a proper Default.png. It’s easy to fall into the temptation to create a cool splash screen but it’s my belief a good Default.png will help “lead” your user into the app and reduces the amount of perceived load time. Apple recommends (http://developer.apple.com/library/ios/#DOCUMENTATION/iPhone/Conceptual/iPhoneOSProgrammingGuide/App-RelatedResources/App-RelatedResources.html) you use a screenshot of your initial view with the text and buttons removed. Here are a few examples of good Default.pngs:

WordPress

Colloquy

Cheddar

In reality, Default.png will only show for a second or so but when properly done, in conjunction with a few of the techniques mentioned by the other guys, can help make your app load feel snappier.

Using custom fonts on iOS (iPhone iPad)

This is a quick walk-through on using a font other than those supplied by Apple on an iOS device.

For reference purposes, you can find out what fonts are available to you “out of the box” by checking out this comprehensive list:
http://iosfonts.com/

I’m going to be using Bebas for my example, a great font created by Dharma Type. You can pick it up here: http://www.dafont.com/bebas.font or use a font of your own choice. It’s important to note you should check a font’s license before you use it in an app you intend to distribute in the app store.

If your font’s not installed on your Mac, go ahead and install it. Before we get too deep into coding and while you’re in or around Font Book let’s go ahead and get the PostScript name of your font. You can do this by selecting your font from the list inside of Font Book and pressing Command + I to toggle the font information. The right side of the window will look like this:

The PostScript name is listed on the top, with Bebas, the PostScript name is simple… it’s Bebas but most are more complicated. Take the PTSans family for example: PTSans-Regular to PTSans-CaptionBold. Keep this PostScript name handy as we’ll reference it later.

Moving on let’s get the ttf file into an Xcode project.

I started with a Single View Application template, go ahead and get that going as normal. Inside my Supporting Files folder I’m going to create a group named “Fonts”. I’m going to drag BEBAS___.TTF into that directory and make sure “Copy items into destination group’s folder (if needed)” is checked. Click finish.

Next, open your app’s plist. Right click and add a row, we’re going to add the key “Fonts provided by application” which is an array of the ttf font files. Toggle that down and for Item 0 add BEBAS___.TTF.

Now you need to head over to your project’s build phases tab. Click to the “Copy Bundle Resources” and click the + icon to add a new item and choose BEBAS___.TTF.

Now, when your window looks like this, you’re ready to use the font in the application:

I put some simple code to create a UILabel in my viewDidLoad method like this:

    UILabel *bebasFlavoredLabel = [[UILabel alloc] initWithFrame: CGRectMake(0, 0, 320, 44)];
    bebasFlavoredLabel.text = @"Bebas on iPhone";
    [bebasFlavoredLabel setFont: [UIFont fontWithName:@"Bebas" size:15]];

    [self.view addSubview: bebasFlavoredLabel];

On line 3 you see where we use [UIFont fontWithName:@"Bebas" size:15]. The name you use there is the PostScript name you found at the beginning. Go ahead and run:

Viola! Your font is ready to be used as you wish!

[Rails] Heroku Image Attachments Using Paperclip and S3

Intro

Heroku is awesome, it makes deployment easy and is an all around great service. However, it does have a few limitations and one of those is the inability to upload files. When we need to do this, we use thoughtbot’s paperclip gem which makes managing file attachments easy coupled with Amazon’s S3 (simple storage service).

Amazon S3

S3, simply put, is cloud storage provided by Amazon. Although it does have a free tier there is a price associated with using S3. As of this writing, the free tier gives you 20,000 GET requests, 2,000 PUT requests and 15gb of data transfer out per month. You can view all of the pricing tiers and information at Amazon’s S3 Pricing Page. To get an estimate of your cost you can head over to Amazon’s cost estimator and clicking “Amazon S3″ on the left. To get started, you’ll need to sign up (note: all sign-ups require a credit card including the free tier). Once you’re in you’ll need to go to your security credentials page under “My Account / Console”:

Once you’re on the security credentials page, you’ll need to scroll down to the “Access Credentials” section and by default you should be on the “Access Keys” tab:

You need to make note of the Access Key ID and then click the “Show” link for your Secret Access Key. Copy these and hang on to them, we’ll need them in just a few minutes. Next we’ll need to create a “Bucket” which for our purposes is similar to a folder. There are several ways you can go about doing this. To create a bucket we’ll use the S3 AWS management console provided by Amazon. In the upper left corner you’ll see the “Create Bucket” button:

Click it. You’ll see a screen like this:

Name your bucket whatever you’d like and select the appropriate region. I’m going to use “US Standard” because… I’m in the US. Then hit the “Create” button. Congratulations, you just created your first bucket. Now let’s code.

Code

You should start by installing the paperclip and S3 gems (we need a gem to communicate back and forth with S3), in your gemfile:

gem 'paperclip'
gem 'aws-s3'

Go ahead and bundle install

Next, much like you have a database.yml in your config folder, you need to create an s3.yml that the S3 gem will use to reference your S3 credentials. The contents of the file should look like this:

access_key_id:      
secret_access_key:  
bucket:             

You should fill this out accordingly based on the information you got from the Security Credentials section of the S3 site and whatever you named your bucket. Update it and save.

Next, we need to update our model to include an attached file. For this tutorial, I’m going to attach an image to a model called User and I’m going to call it Avatar. So here’s what we need to do in the console:

rails generate migration add_avatar_to_users avatar_file_name:string avatar_content_type:string avatar_file_size:integer avatar_updated_at:datetime

Go ahead and run rake db:migrate. So we’re adding 4 properties to our user model: avatar_file_name, avatar_content_type, avatar_file_size, avatar_updated_at. All of these should be self explanatory in case it’s not clear, the content_type property will store information like jpeg, png, etc.

Let’s head over to the model (for me user.rb) and let it know of this new attachment:


has_attached_file :avatar,
  :styles =>{
    :thumb  => "50x50",
    :medium => "400x400"
  },
  :storage => :s3,
  :s3_credentials => "#{Rails.root}/config/s3.yml"",
  :path => ":attachment/:id/:style.:extension",
  :bucket => "the_bucket_name"

On lines 2-5 we’re telling paperclip we want 2 styles of our uploaded image (you can change this to allow for more styles with different sizes). It’ll resize them for us an store 3 copies, the thumb, medium-sized, and the original uploaded image. Just to be clear, it WILL resize these images for us (using ImageMagick). On line 6 we’re identifying the fact that we’d like to use S3 to store this avatar and then on line 7 we define our configuration file’s location. On line 8 we are defining our directory structure for storage on S3. Let’s say you’re a user with the id of 5. If you upload your jpeg avatar, it’ll be stored inside the bucket we specified with the following path: avatar/5/medium.jpg. On line 9 we use the same bucket we created previously.

Now we need to update our views to handle the new avatar. We’ll start with our form to create users (or edit users):

<%= form_for :user, @user, :url => user_path, :html => { :multipart => true } do |form| %>
  <%= form.file_field :avatar %>
<% end %>

This is pretty straightforward, just make sure you’re making the form multipart (to allow for the file upload) and then adding the file field for the avatar. To display this avatar you do the following:

<%= image_tag @user.avatar.url(:thumb) %>

You can, of course, change :thumb to be :medium or whatever style you’ve predefined in the model. For additional reference or to see the other cool things you can do with paperclip, head over here.

Scanning a Bar Code with ZBarSDK

We’re going to focus on scanning UPCs, however I believe the ZBarSDK can be used to scan QRCodes and that may be the topic of another tutorial at a later date (feel free to leave a comment or tweet at me if you would be interested). You can download the sample project here.

To get started I’m going to create a new project and use the Single View template. We’ll need to add a few frameworks to our project:

AVFoundation.framework
CoreMedia.framework
CoreVideo.framework
QuartzCore.framework
libiconv.dylib

You’ll need to download the ZBarSDK from here: http://zbar.sourceforge.net/iphone/ (you’ll need to scroll about halfway down to the section titled “iPhone Developers”. Once you’ve downloaded the DMG file it’s pretty straightforward about how to get the library into your project:

Go ahead and drag the ZBarSDK folder into your XCode project.

In our ViewController’s header we need to import the ZBarSDK header file:
#import "ZBarSDK.h"

Let’s also make our ViewController a ZBarReaderDelegate:
@interface ViewController : UIViewController

While we’re in the header let’s go ahead and declare an IBOutlet for a UIButton named “scanButton”:

IBOutlet UIButton *scanButton;

@property (nonatomic, retain) IBOutlet UIButton *scanButton;

Also be sure to @synthesize:

@synthesize scanButton;

Next we’ll create an IBAction for the scanButton called scanButtonPress:

-(IBAction) scanButtonPress:sender;

Your ViewController’s header should now look like this:


#import <UIKit/UIKit.h>
#import "ZBarSDK.h"

@interface ViewController : UIViewController <ZBarReaderDelegate> {
    IBOutlet UIButton *scanButton;
    
}

@property (nonatomic, retain) IBOutlet UIButton *scanButton;

-(IBAction) scanButtonPress:sender;

@end

Go ahead and create a button in Interface Builder and link it to the outlet and action we’ve created:

Next let’s work on the scanButtonPress action:

-(IBAction)scannerPress:(id)sender{
    
    ZBarReaderViewController *reader = [ZBarReaderViewController new];
    reader.readerDelegate = self;
    
    [reader.scanner setSymbology: ZBAR_UPCA config: ZBAR_CFG_ENABLE to: 0];
    reader.readerView.zoom = 1.0;
    
    [self presentModalViewController: reader
                            animated: YES];
    
}

We’ll go through line by line:

On line 3, we create a new ZBarReaderViewController and on line 4, set our ViewController as the delegate. On line 6-7, we set up the reader and tell it we’re going to be scanning a UPC (ZBAR_UPCA, you can read about the supported symbologies here) and we want the zoom level to be 1.0. Finally, on line 9, we show the reader. If you’ve ever used the UIImagePickerController. This will begin to seem familiar.

Now we need to setup our delegate method — this is pretty vanilla code from the SDK documentation:

- (void) imagePickerController: (UIImagePickerController*) reader
 didFinishPickingMediaWithInfo: (NSDictionary*) info
{
    id<NSFastEnumeration> results = [info objectForKey: ZBarReaderControllerResults];
    
    ZBarSymbol *symbol = nil;
    
    for(symbol in results){
           
        NSString *upcString = symbol.data;
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Scanned UPC" message:[NSString stringWithFormat:@"The UPC read was: %@", upcString] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
        
        [alert show];
        
        [reader dismissModalViewControllerAnimated: YES];
        
    }
    
    
}

Basically the Picker can return multiple results, so we’ll enumerate through those (lines 4-8 — also the for loop). On line 10 we actually pull the UPC result from the data returned from the Picker (ZBarReaderViewController) and then on lines 12 and 14 we display that UPC with an alert and dismiss the ZBarReaderViewController modal on line 16.

Again, this is very vanilla information available to you in the official SDK documentation, which is available here, where you’ll also find additional information about the ZBarSDK.

It’s important to note that because the reader uses the camera you will have to run this on an actual device (not the simulator) to test it.

[Rails] Devise and Active Admin Single User Model

If you’re working on a project that requires an Admin section and you already require authentication for other areas you should really consider using Active Admin with Devise. By default Active Admin uses Devise for it’s authentication but creates a new user model specific to admins. If you already have a user model in place or would like to simply have one user model, there’s not much to it.

To get started, you’ll need to add a few gems to your gem file (if using > Rails 3.1, this assumes you already have sass-rails in your gem file.

Gemfile:

gem 'devise'
gem 'activeadmin'
gem 'meta_search',    '>= 1.1.0.pre'

Go ahead and run bundle install to get those gems installed. We’ll start by configuring Devise. We’re going to create a user model named …wait for it… "User" (unique, I know). If you’ve never used Devise before and want more information, you can check out their readme here. To get going we’re going to run a few generators:

rails generate devise:install

Which generates our Devise installation. Followed by:

rails generate devise User

That generates our user model. Before we rake our user migrations, let’s add a boolean admin flag to the user model:

rails generate migration add_admin_flag_to_users admin:bool

Go ahead and run your migrations:

rake db:migrate

Now, let’s go ahead and install Active Admin — normally, if you’re following the Active Admin docs (available here) you’d run the following command:

rails generate active_admin:install

However, this generates it’s own user model (called AdminUser) that we don’t want. Instead, we’ll run the following command:

rails generate active_admin:install --skip-users

This basically tells Active Admin not to make it’s own model. If you look inside the Active Admin initializer there are, amongst other things, two methods that it uses to a) make sure the user is an admin (config.authentication_method = :authenticate_admin_user!) and b) return the admin user (config.current_user_method = :current_admin_user). Because we’re using our own model we need to define these methods and we’ll do so in the application_controller.rb:

  def authenticate_admin_user!
    authenticate_user! 
    unless current_user.admin?
      flash[:alert] = "This area is restricted to administrators only."
      redirect_to root_path 
    end
  end
  
  def current_admin_user
    return nil if user_signed_in? && !current_user.admin?
    current_user
  end

Now if you have a user that has the admin flag set to TRUE, they’ll be able to browse to /admin and view the Active Admin panel. If they’re not logged in, they’ll be prompted to do so, if they’re not an admin they’ll be redirected to the root path with a flash message informing them of the restricted area.

Twitter on iOS: Tweeting a Tweet, The TweetSheet

Tweeting on iOS hasn’t been easier since iOS 5.

To get started, add the Twitter.framework to your project:





Next, import Twitter.h into your ViewController:

#import <Twitter/Twitter.h>


You’ll probably want to create a new action on a UIButton, so we’ll call that tweetButtonPress:


- (void) tweetButtonPress:sender {
    
}

Inside that method we’ll create a TWTweetComposeViewController, this is what is referred to as the “TweetSheet” and looks something like this:

if([TWTweetComposeViewController canSendTweet]){
//Create the tweetsheet
    TWTweetComposeViewController *tweetSheet = [[TWTweetComposeViewController alloc] init];

//Set initial text of the tweet
[tweetSheet setInitialText: @"Hello Twitter World"];

//Add a completion handler for the tweetsheet
    tweetSheet.completionHandler = ^(TWTweetComposeViewControllerResult result){
        [self dismissModalViewControllerAnimated:YES];
    };

//Show the tweetsheet
[self presentModalViewController:tweetSheet animated:YES];
}

else{
 NSLog(@"Handle inability to send Tweet");
}

Most of this is pretty straightforward but on line 6 we set the initial text of the Tweet. This will be user editable but you can certainly have a “recommended tweet”. On line 1 we check to see that the user can even send a Tweet. There are a few reasons they might not be able to: they may not have a Twitter account setup on their device or they may not currently have an internet connection — you can handle these issues however you please in the else starting on line 17. On lines 9-11 we setup a completion handler that will dismiss the TweetSheet when the user is done. Finally, on line 14 we bring the TweetSheet into the view.

Now, there are a few additional methods you can call to attach images and links to the user’s tweets.

To add a URL to the Tweet:

[tweetSheet addURL:[NSURL URLWithString:@"http://jaysonlane.net"]];

Twitter will automatically shorten this to a t.co link.

To add an image to the Tweet:

[tweetSheet addImage:[UIImage imageNamed:@"image.png"]];

And Twitter will handle the uploading for you. These types of attachments will be displayed on the right side of the TweetSheet held on by the paperclip to let the user know they’ve been added.

Path 2.0 style animated splash screen (default.png)

I don’t use splash screens often but when I do, I want them to open like a book.

In all truth, I’m not a big fan of splash screens and even Apple recommends using a default.png that shows the controls (with no text) of the application:

Display a launch image that closely resembles the first screen of the application. This practice decreases the perceived launch time of your application.

Avoid displaying an About window or a splash screen. In general, try to avoid providing any type of startup experience that prevents people from using your application immediately.

from HIG Guidelines

However, some people love them and one app in particular has a nice implementation splash screen — Path 2.0. When you open Path, you’re greeted with their logo on a red version of the Apple linen texture that animates open like a book (or journal as that’s what Path considers themselves to be).

You can get the source for this project here: https://github.com/jaysonlane/OpenBook

Before we begin, let me preface this with a disclaimer: I am very new to animations in Cocoa so bear with me. If you spot unnecessary or inefficient code, please leave a comment and I’ll tidy it up.

If you haven’t seen the animation, hop on the app store and pick up a copy to see what we’re trying to accomplish. I’ve created a default png that we can use cleverly titled Math (like a Math book that opens, right?) You can download that here (retina) and here.

To get started, let me explain “the trickery” behind what we’ll be doing: we’re going to use the normal default splash system in place to display our default.png. In the App Delegate, once the application has finished launching, we’re going to create a UIImageView on top of our view of that same default.png. We’ll then animate that UIImageView, to rotate open to reveal our view.

So let’s go:

Create a new project, I created one using the single view template but this will work with whatever. Go ahead and set your default.png and default@2x.png to the images supplied. You can do this by clicking the project in the navigation pane on the left, click the Target and scroll down to launch images:

Open your AppDelegate.m and add the following code to your application didFinishLaunching or application didFinishLaunchingWithOptions function:


    //1. add the image to the front of the view...
    UIImageView *splashImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    [splashImage setImage: [UIImage imageNamed:@"Default"]];
    [self.window addSubview:splashImage];
    [self.window bringSubviewToFront:splashImage];

    //2. set an anchor point on the image view so it opens from the left
    splashImage.layer.anchorPoint = CGPointMake(0, 0.5);

    //reset the image view frame
    splashImage.frame = CGRectMake(0, 0, 320, 480);

    //3. animate the open
    [UIView animateWithDuration:1.0
                          delay:0.6
                        options:(UIViewAnimationCurveEaseOut)
                     animations:^{

                         splashImage.layer.transform = CATransform3DRotate(CATransform3DIdentity, -M_PI_2, 0, 1, 0);
                     } completion:^(BOOL finished){

                         //remove that imageview from the view
                         [splashImage removeFromSuperview];
                     }];

Three things are happening here…

1) We create a new UIImageView and add it to the top of the view
2) We set an anchor point on the left side of the image to make it open from the left and then reset the frame to the full size of the view
3) We animate the UIImageView and remove it from the view on completion

That’s it, it’s that simple.

NSDateFormatter

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"YYYY-MM-dd"];

I’ve enjoyed PHP’s date() documentation but have yet to find comprehensive documentation for NSDateFormatter. I have not verified all of the following so if you find an error, leave a comment and I’ll try to get it fixed as quickly as possible. A ton of this information was gathered from Alex Curylo.

Character Description Example Returned Value
a Ante Meridiem and Post Meridiem AM/PM
A Millisecond of the Day 0..86399999
c/cc Numeric representation of day of the week 1..7
ccc Abbreviated day of the week Sun, Mon, Tue…
cccc Written day of the week Sunday, Monday, Tuesday…
d 0 padded Day of Month 1..31
D 0 padded Day of Year 01..366
e Day of Week with leading zero 01..07
E..EEE Sun, Mon, Tue…
EEEE Sunday, Monday, Tuesday…
F Week of Month, first day of week = Monday, with leading zero 1..5
g Julian Day Number (number of days since 4713 BC January 1)
G..GGG Era Designator Abbreviated BC, AD
GGGG Era Designator Before Christ, Anno Domini
h Hour (12 hr) with leading zero 1..12
H Hour (24 hr, starting at 0) with leading zero 0..23
k Hour (24 hr, starting at 1) with leading zero 1..24
K Hour (12 hr) with leading zero 0..11
m Minute with leading zero 0..59
s Second with leading zero 0..59
S Rounded sub-second
v..vvv General GMT Timezone Abbreviation GMT
vvvv General GMT Timezone Name Atlantic/Azores
z..zzz Specific GMT Timezone Abbreviation
zzzz Specific GMT Timezone Name
Z RFC 822 Timezone +0000
L..LL Month with leading 0 01..12
LLL Month abbreviation Jan, Feb, Mar…
LLLL Full Month January, February, March…
w Week of Year, 1st day of week is Sunday, 1st week of year starts from the last Sunday of last year, with leading zero 01..53
W Week of Month, 1st day of week = Sunday, with leading 0 01..05
M..MM Month of the year 1..12
MMM Month Abbreviated Jan, Feb, Mar…
MMMM Full Month January, February, March…
q..qq Quarter of the year 1..4
qqq Quarter abbreviated Q1, Q2, Q3, Q4
qqqq Quarter written out 1st quarter, 2nd quarter, 3rd quarter…
Q..QQ Quarter of the year 1..4
QQQ Quarter abbreviated Q1, Q2, Q3, Q4
QQQQ Quarter written out 1st quarter, 2nd quarter, 3rd quarter…
y/yyyy Full Year 2012, 2013, 2014…
yy..yyy 2 Digits Year 12, 13, 14…
Y/YYYY Full Year, starting from the Sunday of the 1st week of year 2012, 2013, 2014…
YY/YYY 2 Digits Year, starting from the Sunday of the 1st week of year
u Year