Using jQueryMask Plugin to format dates in different patterns

jQuery Mask Plugin is a great Javascript library to format fields for presentation and/or to force a properly input by users.

Here, I show how to deal with input or another HTML element to display dates when the source date has a different format from target element.

Example:

We have a datetime with Year-Month-Day Hour:Minute:Seconds and need to show only the Year/Month/Day part.

We have da date in Year-Month-Day and need to format to Day/Month/Year.

jQueryMask is very simple to use. It do not need to much to mask whatever you need. Take a look at examples on his website.

If you need to format a simple date field (even in a non-input element), just use the code below.

Simple date field mask formatting

JavaScript

1

2

3

4

5

6

7

8

9

jQuery('[data-role="date"]).mask("TC99/M9/D9",{

placeholder:"____/__/__",

translation:{

"D":{pattern:/[0-3]/,optional:false,recursive:true},

"M":{pattern:/[01]/,optional:false,recursive:true},

"T":{pattern:/[12]/,optional:false,recursive:true},

"C":{pattern:/[09]/,optional:false,recursive:true}

}

});

The code above can mask and pre-validate dates in YEAR/MONTH/DAY format.

With an input like

XHTML

1

<input type="text"data-role="date"value="2018-06-11 15:47" />

would be changed his value to 2018/06/11.

If you try to type another date (after clear, of course) you cannot begin with a number different from 1 or 2. This reason is that our mask have a translation to be done when allowing chars. If the pattern does not match, the char is erased.

Compartilhe isso:

Relacionado

Compartilhe em suas mídias sociais

1

Marcos Regis

My name is Regis, Marcos Regis. You can call me Marcos. You can call me Marcos Regis. You can call me Marcos Regis. I'm professional t. I. graduated in data processing Technology for the Community College FATEC.
Atualmente trabalho como desenvolvedor Sênior em uma empresa de médio porte que atua no ramos de logística programando, gerenciando, modelando, organizing and a lot of another ings.

A little bit of your attention!

You are using an ad blocker! So far no more, I also use, but keep this site has cost and the ads are a resource fair. I assure you that the ads displayed will impede you not, portanto pode desativar seu bloqueador sem medo para esse domínio.