I have a date input field that allows the user to enter in a date and I need to validate this input (I already have server side validation), but the trick is that the format is locale dependent. I already have a system for translating the strptime format string to the the user's preference and I would like to use this same format for validating on the Javascript side.
Any ideas or links to a strptime() implementation in Javascript?
After a few days of googling I found this implementation which, although not complete, seems to handle all of the cases I have right now.
I've just added our php.js implementation of strptime(); I've tested it a bit, but it needs further unit testing. Anyhow, feel free to give it a shot; it should cover everything that PHP does (except for not yet supporting the undocumented %E... (alternative locale format) specifiers).
Note that it also depends on our implementation of setlocale() and array_map()...
https://github.com/kvz/phpjs/blob/master/functions/strings/setlocale.js
https://github.com/kvz/phpjs/blob/master/functions/array/array_map.js
Here is an example function that duplicates most of the functionality of strptime. The JavaScript date object generally will parse any date string you throw at it so you don't have to worry to much about that. So once you have a date object based off of your string you just push each element into a JS object and return it. This site has a good reference to the properties of the JavaScript date object: http://www.javascriptkit.com/jsref/date.shtml
function strptime(dateString){
var myDate = new Date(dateString);
return {tm_sec:myDate.getSeconds(),
tm_min: myDate.getMinutes(),
tm_hour: myDate.getHours(),
tm_mday: myDate.getDate(),
tm_mon: myDate.getMonth(),
tm_year: myDate.getFullYear().toString().substring(2),
tm_wday: myDate.getDay()};
}
var dateString = "October 12, 1988 13:14:00";
dateObj = strptime(dateString);
document.write("d:" + dateObj.tm_min + "/" + dateObj.tm_hour + "/" + dateObj.tm_mday + "/" + dateObj.tm_mon + "/" + dateObj.tm_year);
Related
I am trying to convert ISO time local time.
here is my code :
var local_date = new Date('2018-09-11T06:22:39.000-0400');
local_date.toLocaleDateString();
local_date.toLocaleTimeString();
this code is working fine in chrome but in IE its giving error.
first line of code gives me Invalid Date
Looking for a fix which works in all browsers.
FYI: I do not want to use moment.js or any other library, want it in vanilla javascript.
So, the problem is your date-string format.
By reading the Mozilla documentation about the Date Object we can see that your string has to follow the IETF-compliant RFC 2822 timestamps and the ISO8601.
If we open the second one (the ISO8601) we can see that the accepted format is YYYY-MM-DDTHH:mm:ss.sssZ where the Z may be (+|-)HH:mm.
So instead of new Date('2018-09-11T06:22:39.000-0400'); if we execute new Date('2018-09-11T06:22:39.000-04:00'); it works.
If you don't want to add it manually, you can do it automatically by using the splice method from this answer and the code:
// A nice Polyfill
if (!String.prototype.splice) {
String.prototype.splice = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
}
// Your code
var dateString = '2018-09-11T06:22:39.000-0400'.splice(26, 0, ":");
var local_date = new Date(dateString);
local_date.toLocaleDateString();
local_date.toLocaleTimeString();
I don't claim that 2018-09-11T06:22:39.000-0400 is in an invalid format, but an unaccepted by the IE.
Also, if you want to vanilla javascript you should stop opening IE at all.
i am trying to convert milliseconds to my desired date format. But the format that i give to the function doesn`t seem to work.
In my map function
var date = new Date(item.showTime);
var dateString = date.toString('MM/dd/yy HH:mm:ss');
emit([doc.vehicleNumber,doc.advertId],{"seatNumber":item.seatNumber,"showTime":dateString ,"skipTime":item.skipTime});
});
The result is
{seatNumber: 2, showTime: "Tue Nov 21 2017 10:08:56 GMT+0000 (UTC)", skipTime: 0}
I need show time to in format of 10/12/2017 10:08:56.. I don`t know why this is not working.
Btw this is not javascript, i think it is about couchdb so please do
not mark this as duplicate with other JS questions.
CouchDB supports the use of CommonJS Modules in the map function definition.
http://docs.couchdb.org/en/2.1.1/query-server/javascript.html#commonjs
The problem is that modules should be defined in the design document and can not be loaded from external resources.
You can use standard JavaScript built-in objects and functions in your map function as couchjs is based in Mozilla's SpiderMonkey JS interpreter. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
There is not base support in CouchDB JS runtime for date formating. You should write your own logic for this purpose.
If this is a big issue for you, you may try to hack the /path/to/couchdb/share/server/main.js file which is the one that sets the execution contexts of your functions, but I don't see it too much recommendable.
Parse the date and format it yourself. It's not difficult.
var date = new Date(Date.parse(item.showTime));
var timestring = "" + date.getMonth() + "/" + date.getDate() + "/" +
date.getFullYear() + " " + date.toTimeString().substr(0,8)
This is very much about JavaScript. The .toString() method does not take any formatting parameters. You can write your own function to convert the output, or you can use a library that does what you want.
I have a question that I am trying to solve for whole day.
I have Date and Time from Oracle DB that is shown on html page. I have jstl date formatter that has special pattern to show it. Let's take an example 09.05.2017 17:35 +0500 and pattern MM.dd.yyyy HH:mm Z. And I am getting it as String with jQuery . The first case: how to convert it to Date type without any changes. I tryed var date = new Date('09.05.2017 17:35 +0500') but if I have another time zone I'll recieve another UTC and time(hour) or maybe month etc.
Second: how to convert this time to UTC+0300.
I know one solution of this cases, but I think it's not easy. As I have constant pattern of Date, I can always parse the string and to write huge logic for solving second case. I am bad in JS and will be grateful for solution.
Regarding the parsing question, that is answered at Why does Date.parse give incorrect results? The bottom line is that you should parse the string manually and not rely on the built-in parser. A library can help, but if you only have one or two formats to deal with, writing your own parser isn't too difficult.
As for presenting time in a particular timezone, the same advice applies. If you always want UTC+0300, then start by knowing that javascript Dates are always UTC internally and have UTC methods to access those values. So you just change the UTC time by the required offset and format the date as required.
For formatting, see Where can I find documentation on formatting a date in JavaScript?
An example of adjusting the timezone:
// Return a string for UTC+0300 for the supplied date
// in dd-mm-yyyy hh:mm:ss format
function getUTC03(date) {
// Helper to pad with leading zero
function z(n){return ('0'+n).slice(-2)}
// Copy the date so don't affect original
var d = new Date(+date);
// Set UTC time to required offset
d.setUTCHours(d.getUTCHours() + 3);
// Format using UTC methods
return z(d.getUTCDate()) + '-' +
z(d.getUTCMonth()+1) + '-' +
d.getUTCFullYear() + ' ' +
z(d.getUTCHours()) + ':' +
z(d.getUTCMinutes()) + ':' +
z(d.getUTCSeconds()) + ' ' +
'+0300';
}
console.log('Currently at +0300 it\'s ' + getUTC03(new Date()));
However, many places observe daylight saving. To adjust for that, a library is helpful. You just need to provide a location for which the offset can be determined for any particular date and time. Again, there are many questions here about that too.
I'm looking to get a date when literally no time zone is applied in any case. In the example code I get totally different results in IE and Chrome. I need to get "7" in any case. What is the correct way?
$('#result')[0].innerText = "JSon: 2015-03-13T07:30:00 \n" + "As Date: " + new Date("2015-03-13T07:30:00") + "\n" + "Hours Part:" + new Date("2015-03-13T07:30:00").getHours();
https://jsfiddle.net/xtjbvcpw/2/
Thanks.
While this doesn't exactly answer your question, one option would be to use a javascript module to handle the timezone issue (including operating in a fixed and/or arbitrary timezone). I have use moment-timezone in the past to great success.
This Script date.format.js in http://stevenlevithan.com/assets/misc/date.format.js
var txt = 04/04;<br/>
dateFormat(txt, “dd/mm/yyyy”);
result : 04/04/2001
I Want Result : 04/04/2013
You are feeding the function an ambiguous date, don't expect a neat result.
In Firefox, I get "01/01/1970", but if I wrap 04/04 in quotes, so I believe what you I get invalid date, check the js file in line 38 to see why.
What you can do is add the current year pro grammatically like this http://jsfiddle.net/nabil_kadimi/c3Nsf/2/:
var txt = '04/04';
txt += '/' + (new Date()).getFullYear();
window.alert(dateFormat(txt, "dd/mm/yyyy"));
You would want to read this wonderful article on date parsing idiosyncrasies between various browsers.
There are some rules of the thumb provided for working with dates and also about how Chrome is a more accepting browser than others in terms of date formats.