_javascript Techniques for JS date processing using Fecha

Source: Internet
Author: User
Tags fecha i18n string format

Objective

At present, we use the Fecha to date processing in the project, and the Fecha is encapsulated to meet the actual requirements of the project.

Fecha introduction

Fecha is a date format and parsing of the JS library, it provides a powerful date processing function, powerful and only 2k size. Simple installation method, only need npm install fecha --save

Formatting (date formatted)

Fecha provides a format method. fecha.formatreceives a Date object (or a timestamp) and a string format, and then returns a string (the date that is processed).

Note: when the passed parameter is invalid, Fecha will complain

Fecha.format (<date object>, <string format>);

Custom format
//String format can be passed in a custom format, and Fecha returns the corresponding format
fecha.format (New Date (2015,), ' dddd MMMM do, YYYY '); ' Friday November 20th, 2015 '
Fecha.format (New Date (1998, 5, 3,,,,), ' Yyyy-mm-dd hh:mm:ss. SSS A ');//' 1998-06-03 03:23:10.350 PM '/

set the date format with a custom constant
Fecha.format (new Date (2015, a), ' mediumdate '); /' Nov, 2015 '
Fecha.format (New Date (2015, 2, 5, m), ' shorttime ');//' 05:30 '

//Add some other constants
Fecha.form At (New Date (2001, 2, 5, 6, 7, 2, 5), ' [on] mm-dd-yyyy [at] hh:mm '); ' On 03-05-2001 at 06:07 '

So that we can easily deal with new Date() the requirements of the November 19, 2016 →

Fecha.format (New Date (), ' yyyy[year]mm[month]dd[Day] ')

Parsing (date resolution)

Fecha also provides a parse method. Similar to format, Fecha.parse receives a date string and a string format, and then returns a Dates object.

Note: when the passed parameter is invalid, Fecha will complain

Custom Format
formatsfecha.parse (' February 3rd, 2014 ', ' MMMM do, YYYY ');//New Date (2014, 1, 3)
fecha.parse (' 10-12-1 0 14:11:12 ', ' yy-mm-dd HH:mm:ss '); New Date (all, one, one)//the

date format is set by a custom constant

fecha.parse (' 5/3/98 ', ' shortdate ');//new Date (1998, 4, 3)
Fecha.parse (' November 4, the ', ', ' longdate ');//New Date (2005, 10, 4)

Custom named Constants

Fecha.masks = {
 ' default ': ' DDD MMM DD YYYY ',
 shortdate: ' M/d/yy ',
 mediumdate: ' MMM D, YYYY ',
 Longdate: ' MMMM D, YYYY ',
 fulldate: ' dddd, MMMM D, YYYY ',
 shorttime: ' hh:mm ',
 mediumtime: ' HH:mm:ss ', C18/>longtime: ' HH:mm:ss. SSS '
};

Internationalization Support (Outreach)

In the actual use, we will encounter very localized needs, such as to set the "Monday" "Tuesday" "Monday" this strange demand, or Monday need to set to "Lunar Day", Tuesday to set into "Fire Day" and so on

These requirements can be implemented by i18n support mentioned in the parse and format methods.

You can do this by modifying the corresponding setting in fecha.i18n.

fecha.i18n = {
 daynamesshort: [' Sunday ', ' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Friday ', ' Saturday '],
 daynames: [' Sunday ', ' Monday ', ' Tuesday ', ' Wednesday ', '] Thursday ', ' Friday ', ' Saturday ', monthnamesshort: ['], ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ',
 mo Nthnames: [' January ', ' February ', ' March ', ' April ', ' May ', ' June ', ' July ', ' August ', ' September ', ' October ', ' November ', ' December ',
 ampm: [' Morning ', ' PM '],
 //D is The day of the month, a function returns something like ... 3rd or 11th
 dofn:function (d) {return
  D + [' th ', ' st ', ' nd ', ' Rd '] [D% > 3? 0: (d-d% 10!== 10) * D%];
 }

Formatting tokens


Re-encapsulation of the Fecha

In real demand, we also encounter a variety of messy needs

2016-11-20→ tomorrow 11-20
2016-11-23→ next Wednesday 11-23
10:00 Plus 100 minutes of time
...

Although the Fecha provides some very useful date processing methods, but in the strange demand, I still need to fecha encapsulation, to meet the actual needs. And through the encapsulation of Fecha, the extraction of common components, but also to avoid multiple pages i18n configuration and masks settings. Page calls are also more convenient.

Example of a packaged Fecha common component

Import fecha from ' fecha ' fecha.i18n = {daynamesshort: [' Sunday ', ' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Friday ', ' Saturday '], daynames: [' Sunday ', ' Monday ', ' Tuesday ', ' Wednesday ', ' Thursday ', ' Friday ', ' Saturday '], monthnamesshort: [' 01 ', ' 02 ', ' 03 ', ' 04 ', ' 05 ', ' 06 ', ' 07 ', ' 08 ', ' 09 ', ' 10 ', 
 ' One ', ' one ', monthnames: [' January ', ' February ', ' March ', ' April ', ' May ', ' June ', ' July ', ' August ', ' September ', ' October ', ' November ', ' December ', ampm: [' Morning ', ' PM '], D is the ' month, function returns something like ... 3rd or 11th dofn:function (d) {return d + [' th ', ' st ', ' nd ', ' Rd '] [D% &gt; 3? 0: (d-d%!==) * d% 1
 0]; } fecha.masks = {' Default ': ' DDD MMM DD YYYY ', shortdate: ' M/d/yy ', mediumdate: ' MMM D, YYYY ', longdate: ' MMMM D, YYYY ', fulldate: ' dddd, MMMM D, YYYY ', Shorttime: ' hh:mm ', mediumtime: ' HH:mm:ss ', longtime: ' HH:mm:ss. 
SSS '}; STR must be YYYYMMDD format//YYYYMMDD→XX (Today/Tomorrow/Next Monday ...).
 MM month DD Day fecha.getdatestring = (str, format) =&gt; {Let now = Date.now ();
 Let today = Fecha.format.bind (null, New Date ()); Let tomorrow = Fecha.forMat.bind (NULL, new Date (now + 86400 * 1000));

 Let dayafter = Fecha.format.bind (null, new Date (now + 86400 * 2 * 1000));

 Let Week_start = parseint (Today (' d '));
 Let result = {};
 From Monday to the next Sunday a total of 14 let weeks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
 Result[today (YYYYMMDD)] = ' Today ${today (' MM ')} month ${today (' DD ')} day ';
 Result[tomorrow (YYYYMMDD)] = ' Tomorrow ${tomorrow (' MM ')} month ${tomorrow (' DD ')} day ';

 Result[dayafter (YYYYMMDD)] = ' The day After Tomorrow ${dayafter (' MM ')} month ${dayafter (' DD ')} day ';
  Weeks.slice (Week_start + 3). ForEach (after) =&gt; {let step = After-week_start;
  Let _dayafter = Fecha.format.bind (null, new Date (now + 86400 * Step * 1000)); Result[_dayafter (YYYYMMDD)] = ' ${' (after &lt; 8?
 ' Ben ': ' Under ')}${_dayafter (' DDD ')} ${_dayafter (' MM ')}-${_dayafter (' DD ')} '; /////If the next Monday situation occurs, the format specification that is passed in at the time of the output call Format (Fecha.parse (str, YYYYMMDD), format)} export default Fecha

When other pages need to use date processing, simply call the Fecha component on the page.

Import dateparser from ' fecha ' ...
 Let date = dateparser.getdatestring (' 20161123 ', ' yyyy-mm-dd ') ...

When the existing date processing does not solve the actual need, simply add the method to the Fecha component. Write notes, and subsequent colleagues to develop the same function can be called directly, improve the efficiency of the team.

Summarize

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.