Giter VIP home page Giter VIP logo

jquery-dateformat's Introduction

jquery-dateFormat - jQuery Plugin to format Date outputs using JavaScript - Having less than 5kb, jquery-dateFormat is the smallest date format library available!

build passing

Installation

Download latest jquery.dateFormat.js or jquery.dateFormat.min.js.

You can use jquery-dateFormat without jQuery. You just need to import the dateFormat.js above and instead of formatting with $.format(...) you should use DateFormat.format(...).

If you use jQuery Validate plugin you must use jquery-dateFormat without jQuery.

Format patterns

The patterns to formatting are based on java.text.SimpleDateFormat.

Date and time patterns

  • yy = short year
  • yyyy = long year
  • M = month (1-12)
  • MM = month (01-12)
  • MMM = month abbreviation (Jan, Feb ... Dec)
  • MMMM = long month (January, February ... December)
  • d = day (1 - 31)
  • dd = day (01 - 31)
  • ddd = day of the week in words (Monday, Tuesday ... Sunday)
  • E = short day of the week in words (Mon, Tue ... Sun)
  • D - Ordinal day (1st, 2nd, 3rd, 21st, 22nd, 23rd, 31st, 4th...)
  • h = hour in am/pm (0-12)
  • hh = hour in am/pm (00-12)
  • H = hour in day (0-23)
  • HH = hour in day (00-23)
  • mm = minute
  • ss = second
  • SSS = milliseconds
  • a = AM/PM marker
  • p = a.m./p.m. marker

Expected input dates formats

  • 1982-10-15T01:10:20+02:00
  • 1982-10-15T01:10:20Z
  • Thu Oct 15 01:10:20 CET 1982
  • 1982-10-15 01:10:20.546
  • Thu Oct 15 1982 01:10:20 GMT-0800 (PST)
  • Thu Oct 15 1982 01:10:20 GMT+0800 (China Standard Time)
  • Thu Oct 15 1982 01:10:20 GMT+0200 (W. Europe Daylight Time)
  • 1982-10-15CET01:10:20
  • JavaScript: new Date().getTime()

Some examples.

Usage

 <script>
   document.write($.format.date("2009-12-18 10:54:50.546", "Test: dd/MM/yyyy"));
   document.write($.format.date("Wed Jan 13 10:43:41 CET 2010", "dd~MM~yyyy"));
 </script>

Output

 => Test: 18/12/2009
 => 13~01~2010

Formatting using css classes

  <span class="shortDateFormat">2009-12-18 10:54:50.546</span>
  <span class="longDateFormat">2009-12-18 10:54:50.546</span>
  jQuery(function() {
      var shortDateFormat = 'dd/MM/yyyy';
      var longDateFormat  = 'dd/MM/yyyy HH:mm:ss';

      jQuery(".shortDateFormat").each(function (idx, elem) {
          if (jQuery(elem).is(":input")) {
              jQuery(elem).val(jQuery.format.date(jQuery(elem).val(), shortDateFormat));
          } else {
              jQuery(elem).text(jQuery.format.date(jQuery(elem).text(), shortDateFormat));
          }
      });
      jQuery(".longDateFormat").each(function (idx, elem) {
          if (jQuery(elem).is(":input")) {
              jQuery(elem).val(jQuery.format.date(jQuery(elem).val(), longDateFormat));
          } else {
              jQuery(elem).text(jQuery.format.date(jQuery(elem).text(), longDateFormat));
          }
      });
  });

Output

 => 18/12/2009
 => 18/12/2009 10:54:50

Pretty date formatting

jQuery.format.prettyDate(value) returns a string representing how long ago the date represents

  • value = String representing ISO time or date in milliseconds or javascript Date object
 jQuery.format.prettyDate(new Date())             // => "just now"
 jQuery.format.prettyDate(new Date().getTime())   // => "just now"
 jQuery.format.prettyDate("2008-01-28T20:24:17Z") // => "2 hours ago"
 jQuery.format.prettyDate("2008-01-27T22:24:17Z") // => "Yesterday"
 jQuery.format.prettyDate("2008-01-26T22:24:17Z") // => "2 days ago"
 jQuery.format.prettyDate("2008-01-14T22:24:17Z") // => "2 weeks ago"
 jQuery.format.prettyDate("2007-12-15T22:24:17Z") // => "more than 5 weeks ago"

toBrowserTimeZone

jQuery.format.toBrowserTimeZone(value, format) converts into browsers timezone.

  • value = String representing date in ISO time ("2013-09-14T23:22:33Z") or String representing default JAXB formatting of java.util.Date ("2013-09-14T16:22:33.527-07:00") or String representing Unix Timestamp (Sat Sep 14 2013 16:22:33 GMT-0700 (PDT)) or javascript date object.
  • format = All input formats valid for jQuery.format.date are valid for this method. The defaut format is MM/dd/yyyy HH:mm:ss.

Valid input formats

 var date1 = "2013-09-14T23:22:33Z";
 var date2 = "2013-09-14T16:22:33.527-07:00";
 var date3 = "Sat Sep 14 2013 16:22:33 GMT-0700 (PDT)";

 $.format.toBrowserTimeZone(date1)
 $.format.toBrowserTimeZone(date2)
 $.format.toBrowserTimeZone(date3)

Development

To compile jquery-dateFormat (generate dist files):

npm run compile

Testing

Tests are written using Jasmine. To run the test suite with PhantomJS, run npm run test. To run the test suite in your default browser, run npm run test:browser.

Licenses

jquery-dateFormat is released under the MIT License.

Do you want to improve jquery-dateFormat

You're welcome to make your contributions and send them as a pull request.

Contributors

Thanks to all contributors.

jquery-dateformat's People

Contributors

andreycarter avatar argentinaluiz avatar arjunballa avatar buholzer avatar cjxd avatar dahdread avatar daviscabral avatar docchang avatar drcreazy avatar dwaxweiler avatar enhan avatar fero avatar gnashdrw avatar hafeyang avatar jafin avatar jharting avatar jonathanargentiero avatar joostory avatar jwadhams avatar merge-when-green[bot] avatar mikedemers avatar peerb avatar phstc avatar px-factor avatar rdgr avatar ssproessig avatar tfrajt avatar thiloplanz avatar vejuhust avatar zyber17 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-dateformat's Issues

Full ISO8601 compatibility

2010-10-19T11:40:33.527+02:00 works but not this 2012-02-14T04:40:51.229Z

According to the W3C specs, the time zone designator format (the last characters in the example) should be in Z, +hh:mm, -hh:mm.

Update nuget package

The latest versions as far as I can determine is 1.0 (file) and 1.01 (package) (out of sync)? Latest release appears to be 1.0.2. Thanks!

Date format/pattern

Hi,

Why didn't you use format/pattern by standard, as on other platforms?

Doesn't work with jQuery Validate plugin

I had the following working
alert(jQuery.format.date(new Date(), "MMM d, yyyy"));
But when I included jQuery Validate plugin, the alert stopped appearing. Find below the source code.

<script type="text/javascript" src="jscript/jquery-1.8.3.js"></script>
<script type="text/javascript" src="jscript/jquery-dateFormat.min.js"></script>
<script type="text/javascript" src="jscript/jquery.validate.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
    alert("hello");
    alert(jQuery.format.date(new Date(),"MMM d, yyyy"));//I have stopped getting this
    jQuery.validator.addMethod("nospace",function(value,element){
        return value!="" && value.indexOf(" ")<0;
    },"No spaces allowed.");

        jQuery("#mktForm_1012").validate({
        rules: {
            Email: {required: true, email: true, nospace: true},
            uPassword: {required: true}
        },
        messages: {
            Email: {required: "Email is required.", email: "Must be a valid email."},
            uPassword: {required: "Password is required."}
        },
        onfocusout: false, onkeyup: false, onclick: false,
        success: function(label) {
            label.html("");
        },
        submitHandler: function(form) {
            //do stuff that uses jQuery.format.date()

        }
    });//end jQuery(form).validate()

});//End jQuery(document).ready(...) call
</script>

Form ids and input field ids are ok and nothing like jQuery("#notExistingElement") contributes to errors. So

Incorrect handling of "08" and "09" months

If you pass in a value of "08" or "09" for month, the code uses parseInt which returns 0 for both of these. The fix is to add a second argument of 10 to the parseInt function to define the base for converting the number. For example:

function strMonth(value) {
var monthArrayIndex = parseInt(value, 10) - 1;
return shortMonthsInYear[monthArrayIndex] || value;
}

    function strLongMonth(value) {

var monthArrayIndex = parseInt(value, 10) - 1;
return longMonthsInYear[monthArrayIndex] || value;
}

Instead of:

function strMonth(value) {
var monthArrayIndex = parseInt(value) - 1;
return shortMonthsInYear[monthArrayIndex] || value;
}

    function strLongMonth(value) {

var monthArrayIndex = parseInt(value) - 1;
return longMonthsInYear[monthArrayIndex] || value;
}

Zulu w/o colon

To support formats that don't incude the final colon in the time zone offset, you need to change the regex:

$.format.date("2011-09-22T05:02:55.889+0000", "dd/mm/yyyy hh:mm:ss")
// fails because "+0000" doesn't include a colon, but this is a valid alternate format for ISO 8601

"The following times all refer to the same moment: "18:30Z", "22:30+04", "1130-0700", and "15:00-03:30" (http://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators)

It's a single character fix:

line 93:
} else if (value.search(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.?\d{0,3}[-+]?\d{2}:\d{2}/) != -1) { /* 2009-04-19T16:11:05+02:00 /
should be:
} else if (value.search(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.?\d{0,3}[-+]?\d{2}:?\d{2}/) != -1) { /
2009-04-19T16:11:05+02:00 */

(there's a question mark after the final colon to match zero or one colon).

DateFormat.format.parseDate missed Time ?

I use dateFormat.js without jquery plugin

DateFormat.format.parseDate("2015-01-16 12:55:54","yyyy-MM-dd HH:mm:ss")
/*returns object{
    date: Fri Jan 16 2015 00:00:00 GMT+0800 (**标准时间) , // missing Time ? "00:00:00" ?
    time:{hour:"12",millis:"",minute:'55","second":"54",time:"12:55:54"}
}*/

Different time

Hello

I am building a site in which I am using your plugin.
For some users the time shows with minus one hour than the actual time.
The date is stored in a postgres database as timestamp without timezone.

Can you give me some pointers why this might happen?

Thank you.

pad with 0

hi,
I need to format a date that I get in this format

2013-04-17 15:10:15

or

2013-04-17 14:3:25

if the time unit is just a single digit, it is not padded with 0.

How can I format it to a zero padded date ?

Using

$.format.date("2013-17-04 10:8:1", "Test:  MMM dd yyyy HH:mm:ss")  

will format it to (missing 0 in the minutes)

Apr 17 2013 14:3:25

SimpleDateFormat would format it to

Apr 17 2013 14:03:25

cheers

some sort of conflict with jquery validate plugins

I'm trying to use dateFormat in an MVC 3 application but this plugin and jquery.validate.js and/or jquery.validate.unobtrusive.js are conflicting. When the page loads I get the error, "$.format.date is not a function". If I leave the validate plugins off the page I don't get this error, however the rest of the application that is using Telerik MVC controls stop functioning because they require the validate plugins.

Is there a way to have the dateFormat work when the validate plugins are included in the page?

Example usage:

function PlanDetail(data, parent) {
// private members
var internal = this;

// public members
this.Name = ko.observable(data.Name);
this.DaysRemaining = ko.observable(data.DaysRemaining);
this.PlanEndDate = ko.observable(data.PlanEndDate);
this.PlanStartDate = ko.observable(data.PlanStartDate);
this.isEditMode = ko.observable(false);

this.FormatedStartDate = ko.computed(function () {
    if (this.PlanStartDate()) {
        return $.format.date(this.PlanStartDate(), "dddd, dd MMMM yyyy");
    }
}, this);

}

Bower: Unexpected token n

Hi folks,

I can't install jquery-dateFormat with bower because of an Unexpected token n.
Unfortunately, I can't find any errors in the bower.js file...

dateFormat fails if no time present (Partial Fix inside)

So I'm working on a project where I was using dateFormat for formatting various kinds of dates client-sided. It worked great until I noticed dates that didn't have time ("2016-06-11") would return an error (IndexOf is undefined) and not format the date. After a quick snoop around I figured it was because the calculations didn't return a Number, so it failed to run the parseTime function.

Here's the problematic code (Line 180 in current dist):

subValues = values[0].split('');
parsedDate.year       = subValues[0] + subValues[1] + subValues[2] + subValues[3];
parsedDate.month      = subValues[5] + subValues[6];
parsedDate.dayOfMonth = subValues[8] + subValues[9];
parsedDate.time       = parseTime(subValues[13] + subValues[14] + subValues[15] + subValues[16] + subValues[17] + subValues[18] + subValues[19] + subValues[20]);
break;

Add a simple line to fix it:

subValues = values[0].split('');
parsedDate.year       = subValues[0] + subValues[1] + subValues[2] + subValues[3];
parsedDate.month      = subValues[5] + subValues[6];
parsedDate.dayOfMonth = subValues[8] + subValues[9];
if(!isNaN(subValues[13] + subValues[14] + subValues[15] + subValues[16] + subValues[17] + subValues[18] + subValues[19] + subValues[20]))
parsedDate.time       = parseTime(subValues[13] + subValues[14] + subValues[15] + subValues[16] + subValues[17] + subValues[18] + subValues[19] + subValues[20]);
break;

After that change, you can now use date-only formats with the plugin. Can someone confirm this was an issue or if time-less dates are not intended.

The only issue I am getting now is reverse-year formats, where the year is at the end of the format such as "11-05-2016" would return an invalid date. Any ideas?

IE browser issue

vat newDateVal = $.format.date(datestr, configDateFormat)
I am using the above code for getting formatted date.
datestr = my date of birth value
configDateFormat = this is my custom format

newDateVal = this is my out put

it's working fine in Crome and Firefox

But not working in IE displaying like Nan,Nan,NaN

Leading 0 for "SSS"(milliseconds) is missing

For $.format.date(new Date(), 'MM/dd/yyyy HH:mm:ss.SSS'), its output is 04/15/2015 21:29:46.79, which would be better with leading 0 in milliseconds, like this 04/15/2015 21:29:46.079.

Issue with non zero leading month 'M' format

Looks like there is something amiss with the formatting of months when you do not included the leading zero ("MM" vs "M").

$.format.date("2016-07-01T00:00:00", "d-M-yyyy");
fails - returns "1-M-2016" not "1-7-2016" as expected.

$.format.date("2016-07-01T00:00:00", "d-MM-yyyy");
returns "1-07-2016" as expected

date format not work

var formattedDate = $.format.date("2011-04-25T09:04:14.7270000", "yyyy-MM-dd HH:mm");
console.log(formattedDate);

the result is still 2011-04-25T09:04:14.7270000

"d" format disappeared

I was using the "d" format and at some point it disappeared from the library. Was there a reason (nasty, performance, etc.)? If so how would you recommend getting a format to look like "January 9, 2012"?

A test might look like:

testShortDay: function() { with(this) {
    assertEqual('January 9, 2012', $.format.date('Wed Jan 09 06:23:38 PST 2012', 'MMMM d, yyyy'));
}}

"h" format throws exception causing blank date during conversion

If you use "h" formatting on an hour > 12 the value is actually an integer and throws an exception if you try to substr it. This results in no result at all. I've fixed it by checking it's a string before calling substr(). Attached below.

case "h":
    if (format.charAt(i + 1) == "h") {
        break;
    }
    /* time.hour is "00" as string == is used instead of === */
    var hour = (time.hour == 0 ? 12 : time.hour < 13 ? time.hour : time.hour - 12);
    if (typeof hour == 'string' && hour < 10) {
        hour = hour.substr(1, 1);
    }                               
    retValue += hour;
    pattern = "";
    break;

Return formated date problem

Hello,

I am using the plugin without jquery, but when I try it

DateFormat.format.date("Mon Apr 28 2014 05:30:00 GMT-0300", "dd/MM/yyyy HH:mm")

The return value is "28/04/GMT-0300 00:00"

Can you help me?

jQuery vs. dollar sign

When using this plugin, which is a great plugin btw, if you are using jQuery in conflict mode, it fails due to the fact that it is coded with the shortcut "$" instead of standard "jQuery".

example...

$.format = (function () {
function strDay(value) {
....

should it not be as follows?

jQuery.format = (function () {
function strDay(value) {

Thanks

M

Prettydate: "more than 5 weeks ago" configurable?

Hi, we like the "prettyDate" function, but just for recent dates (less than 1 month).
For more than 1 month of difference, we prefer to get the exact date.

So, we changed that line:
} else if (day_diff >= 31) {
return $.format.date(date,"yyyy-MM-dd")
}
I don't want to push it as the "default action" for all jquery-dateformat users, but, can it be a configurable feature?
Thank you

Conflict with jQueryValidate

I am using the pure JS version without the jQuery, it still conflicts with it. Could you detail, why there is a conflict?

toBrowserTimeZone with ISO 8601 input

I was excited to see the inclusion of toBrowserTimeZone, but I'm unable to get it to work with ISO 8601 input. For example, $.format.date("2013-09-13T09:44:00Z", "d-MMM-yy hh:mm a") will return "13-Sep-13 09:44 AM" regardless of the browser time zone.

📌 #124

is 'format.date' converting automatically to browser timezone?

It seems when I provide a new Date().getTime() for Unix epoch timestamp (which in Javascript is default to UTC) to the format.date function, it formats my time according to the browser's timezone.
Is there a way to format without automatically converting to the browser's timezone? Meaning, timezone conversion can be manually done.

Day of week is invalid

Hi,
I used $.format.date(new Date('2014-10-25'), "E") it display "Fri" from US and "Sat" from Sri Lanka

Actual day is "Sat", why this show "Fri" for US ?

/Premila

Two digits year support (aka "yy")

Hi,
First i would like to thank you for the amazing work you have done and sharing it with us - the community.

Currently the year can be formatted only in one way - yyyy (4 digits). There is no support for the short year formating (yy). This is a small change and I have implemented it for me but i think it could be useful to include it in the library.

I do not know if i can upload files here so that i will simply paste my changes here :
case "yy":
if (format.charAt(i + 1) == "y" &&
format.charAt(i + 2) == "y") {
break;
}
retValue += String(year).slice(-2);
pattern = "";
break;

and of course I added a few tests to make sure it works (and would keep working) fine:

testShortYear: function() { with(this) {
assertEqual(11, $.format.date('Mon Feb 28 2011 17:45:00 GMT-0400 (Eastern Daylight Time)', 'yy'));
assertEqual(12, $.format.date('Mon Feb 28 20112 17:45:00 GMT-0400 (Eastern Daylight Time)', 'yy'));
assertEqual('13.01.10', $.format.date('Wed Jan 13 10:43:41 CET 2010', 'dd.MM.yy'));
}}

variable scope issue in format.date

need to force encapsulation of variable i in
for (i = 0; i < format.length; i++) on line 104.
Otherwise callee -who may have an "i" defined- will get it's "i' messed up. Change to
for (var i = 0; i < format.length; i++)

Please support future date

Hi,
Preetty Date has a awesome date formatting for all the past date however when I tried to use it for one of my Web application, and it blotted as under (writing this as time '2016-03-22 00:00:00' shows 4 hours ago which is OK considering the server time)

Example 1: Future Date
"Event Date:" + jQuery.format.prettyDate('2016-03-29 19:08:00');

Event Date: undefined

Example 2: Few Hours ahead
"Event Date:" + jQuery.format.prettyDate('2016-03-22 06:00:00');

Event Date: undefined

what is expected in these scenarios:
Example 1

Event Date: 7 days to go
OR
Event Date: 7 days, x hours to go

Example 2

Event Date: x hours to go

Not working in Safari Snow Leopard

Hi,

Here is a simplified code to reproduce issue:

alert($.format.date(new Date(time), "yyyy-MM-dd HH:mm:ss"));

It works correctly in Chrome for Snow Leopard:

2012-04-27 16:25:04

but not in Safari:

NaN-NaN-NaN ::

I changed JS code to:

alert($.format.date(""+new Date(time), "yyyy-MM-dd HH:mm:ss"));

Added double quotes to cast to a JS String.

Still working in Chrome, but not Safari:

Invalid-undefined-undefined ::

Any idea ?

Thank you.

d and dd and M and MM

If you look at the SimpleDateFormat spec you should handle dd an d differently

dd should force there to be 2 digits as well as MM

1-1-2001 = d-M-yyyy
01-01-2001 = dd-MM-yyyy

Bower support

Seems the plugin is already registered but does not include a bower.json file specifying ignores. Would love to see more complete bower support.

📌 #124

dateFormat Completely Stopped Working All of a Sudden

I have had the dateFormat 1.0 plugin deployed on several sites for many months without issue. I just went to one of the pages that utilizes the plugin and the JavaScript breaks at the point that $.format.date() is called. I checked other pages/sites and the exact same thing occurs. When I remove that line of code the JavaScript runs through to the end. I am the only admin for these sites and I have not made any changes in weeks. Is there an issue because we rolled over calendar years? This failure is causing whole pages to render incorrectly. Your help will be greatly appreciated.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.