I am using jqm-calendar for my jquery mobile app. Right now the default time format is 24 hours. I would like to change it to 12 hours.
Thank you.
https://github.com/JWGmeligMeyling/jqm-calendar
In file jw-jqm-cal.js
add this function:
function tConvert (time) {
// Check correct time format and split into components
time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
if (time.length > 1) { // If time format correct
time = time.slice (1); // Remove full string match value
time[5] = +time[0] < 12 ? ' AM' : ' PM'; // Set AM/PM
time[0] = +time[0] % 12 || 12; // Adjust hours
}
return time.join (''); // return adjusted time or original string
}
and insert this 2 lines in function plugin.settings.eventHandler.getEventsOnDay(begin, end, function(list_of_events):
beginTime =tConvert(beginTime );
endTime=tConvert(endTime);
EDIT
insert before: timeString = beginTime + "-" + endTime :**
...
beginTime =tConvert(beginTime );
endTime=tConvert(endTime);
timeString = beginTime + "-" + endTime,
...
Related
I want to add 30 days to a Date (including the timestamp), however, the timestamp is being calculated from the execution time of the script instead of the source data (loadStartDateTime).
I created a new date object and then set the date (purge_date = loadStartDateTime + 30days).
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
PURGEDATE = (function (loadTime) {
var loadDate = new Date(loadTime);
var purge_date = new Date();
purge_date.setDate(loadDate.getDate()+30);
var month = purge_date.getMonth() + 1;
var mm = month < 10 ? "0" + month : month;
var day = purge_date.getDate();
var dd = day < 10 ? "0" + day : day;
var hours = purge_date.getHours() < 10 ? "0" + purge_date.getHours() : purge_date.getHours();
var minutes = purge_date.getMinutes() < 10 ? "0" + purge_date.getMinutes() : purge_date.getMinutes();
var seconds = purge_date.getSeconds() < 10 ? "0" + purge_date.getSeconds() : purge_date.getSeconds();
var time = hours + ":" + minutes + ":" + seconds;
var yyyy = purge_date.getFullYear();
return mm + "/" + dd + "/" + yyyy + time;
})(LoadStartDateTime)
The Result:
loadStartDateTime | PurgeDate
8/7/2018 5:55:45 PM | 09/06/2018 10:28:49
8/7/2018 5:58:10 PM | 09/06/2018 10:28:49
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
Thank you~
After further investigation I realized that:
The Date object’s constructor is ISO 8601
When I use getDate() I do not provide the timezone explicitly.
This causes the timestamp to be 00:00:00 local time, so I should use getTime() method instead to get the timestamp. Since in JavaScript a timestamp is the number of milliseconds, a simple way to get it done is to send the timestamp value in the Date constructor. To calculate 30 days measured in timestamp:
30 * 24 * 60 * 60 * 1000
Finally, sum both values and send the result as a param in the constructor:
For example:
loadStartDateTime = new Date('8/7/2018 5:55:45 PM');
test_date = loadStartDateTime.getTime() + (30 * 24 * 60 * 60 * 1000);
test_date = new Date(test_date);
and then can continue with the Date Formatting.
I found the solution combining the answers from ISO 8601 date format - Add day with javascript and Add 30 days to date (mm/dd/yy). This guide "The Definitive Guide to DateTime Manipulation" helped to find out when I was wrong by understanding more about DateTime Manipulation.
I need to convert my time that is in military time 24 hours time to regular 12/12 time.
nextArrivalFinal2 = ((hour > 0 ? hour + ":" + (min < 10 ? "0" : "") : "") + min + ":" + (sec < 10 ? "0" : "") + sec);
console.log("nextArrival2", typeof nextArrivalFinal2)
console.log("nextArrival2", nextArrivalFinal2)
var convertedDate = moment(new Date(nextArrivalFinal2));
console.log('converted1', convertedDate)
console.log('converted', moment(convertedDate).format("hh:mm:ss"));
nextArrivalFinal2 displays the time as a string in HH:MM:ss format. But when I plug it into the moment js, it says it is an invalid date.
You are not parsing the time with moment.js, the line:
var convertedDate = moment(new Date(nextArrivalFinal2));
is using the date constructor to parse a string like "13:33:12", which will likely return an invalid date in every implementation (and if it doesn't, it will return something that may be very different to what you expect).
Use moment.js to parse the string and tell it the format, e.g.
var convertedDate = moment(nextArrivalFinal2, 'H:mm:ss'));
Now you can get just the time as:
convertedDate().format('h:mm:ss a');
However, if all you want is 24 hr time reformatted as 12 hour time, you just need a simple function:
// 13:33:12
/* Convert a time string in 24 hour format to
** 12 hour format
** #param {string} time - e.g. 13:33:12
** #returns {sgtring} same time in 12 hour format, e.g. 1:33:12pm
*/
function to12hour(time) {
var b = time.split(':');
return ((b[0]%12) || 12) + ':' + b[1] + ':' + b[2] + (b[0] > 12? 'pm' : 'am');
}
['13:33:12','02:15:21'].forEach(function(time) {
console.log(time + ' => ' + to12hour(time));
});
So i have a json object, which returned me basically a datetime object, now the question, what is the most efficient way of formatting this to a single string human readable format, in the users (client) local timezone... In javascript
created: {
timezone: {
name: "America/New_York",
location: {
country_code: "US",
latitude: 40.71417,
longitude: -74.00639,
comments: "Eastern Time"
}
},
offset: -18000,
timestamp: 1454125056
},
If the timestamp is an ECMAScript time value (i.e. milliseconds since 1970-01-01T00:00:00Z) then you can give that value directly to a Date object:
var d = new Date(1454125056); // 1970-01-17T19:55:25.056Z
however it is more likely seconds, so multiply by 1,000:
new Date(1454125056*1000).toISOString(); // 2016-01-30T03:37:36.000Z
which will create a Date for that moment in time. The offset should probably be ignored, unless it was used in the creation of the time value, in which case it should be added if it follows the ISO convention of negative for west and positive for east. If it follows the ECMAScript convention, the opposite applies.
I'll assume ISO, and since it appears to be seconds, you can apply it to the UTC seconds:
var offset = -18000;
d.setUTCSeconds(d.getUTCSeconds() + offset);
console.log(d.toISOString()); // 2016-01-29T22:37:36.000Z
Using plain Date methods thereafter will return values based on the host system's timezone settings.
var timeValue = 1454125056;
var offset = -18000;
var d = new Date(timeValue*1000);
document.write(d.toISOString() + '<br>' + d);
d.setUTCSeconds(d.getUTCSeconds() + offset);
document.write('<br>' + d.toISOString() + '<br>' + d);
There are many questions here on how to format a date string from a Date object.
Note that javascript is only required consider the daylight saving rules in force at the current time as if they had always existed, so be careful with historical dates.
Suppose this json object loaded in $created variable. i assume you mean php.
in PHP :
$obj = json_decode($created, true);
$timezone_name = $obj['timezone']['name'];
$timezone_location_country_code = $obj['timezone']['location']['country_code'];
$timezone_location_latitude = $obj['timezone']['location']['latitude'];
$timezone_location_longitude = $obj['timezone']['location']['longitude'];
$timezone_location_comments = $obj['timezone']['location']['comments'];
$offset = $obj['offset'];
$timestamp = date('m/d/Y', abs($obj['timestamp']));
in Javascript :
getDate: function(timestamp){
// Multiply by 1000 because JS works in milliseconds instead of the UNIX seconds
var date = new Date(timestamp * 1000);
var year = date.getUTCFullYear();
var month = date.getUTCMonth() + 1; // getMonth() is zero-indexed, so we’ll increment to get the correct month number
var day = date.getUTCDate();
var hours = date.getUTCHours();
var minutes = date.getUTCMinutes();
var seconds = date.getUTCSeconds();
month = (month < 10) ? ‘0’ + month : month;
day = (day < 10) ? ‘0’ + day : day;
hours = (hours < 10) ? ‘0’ + hours : hours;
minutes = (minutes < 10) ? ‘0’ + minutes : minutes;
seconds = (seconds < 10) ? ‘0’ + seconds: seconds;
return year + ‘-‘ + month + ‘-‘ + day + ‘ ‘ + hours + ‘:’ + minutes;
}
This is an easy thing to do in PHP with code like this;
if (strtotime($given_time) >= time()+300) echo "You are online";
But can't find anything on SO to do exactly this in javascript.
I want to check if the difference between a given time and the current time is less than 45mins
For instance
$scope.given_time = "14:10:00"
$scope.current_time = new Date();
I'm only concerned with the time part. I need to extract time part from new Date(); and then compare.
Then this should be true
How can I achieve this with Javascript:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Javascript uses unix timestamps in milliseconds, so it is similar to the output of strtotime (which uses seconds).
var date = new Date();
Then you'll need to do the calculation from milliseconds. (Minutes * 60 * 1000)
You can also use date.parse() to parse a string to milliseconds, just like strtotime() in PHP does to seconds.
In full:
var date = new Date();
var last = new Date('Previous Date'); // or a previous millisecond timestamp
if ( ( date - last ) > ( 45 * 60 * 1000 ) ) {
// do something
}
You could use a static date to compare just time, this is exactly what strtotime does if you exclude the date:
var last = new Date('1/1/70 14:10:00');
var date = new Date('1/1/70 14:30:00');
However, this approach will fail if you're trying to compare time that cross over day boundaries.
Try this:
function checkTime(time) {
var date = new Date();
var date1 = new Date((date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + time);
var minutes = (date1.getTime() - date.getTime()) / (60 * 1000);
if (minutes > 45 || (minutes < 0 && minutes > -1395)) {
// greater than 45 is todays time is above 45 minutes
// less than 0 means the next available time will be tomorrow and the greater than -1395 means it will be more than 45 minutes from now into tomorrow
document.write(time + ': true<br />');
} else {
document.write(time + ': false<br />');
}
}
checkTime("14:10:00");
checkTime("16:30:00");
checkTime("17:10:00");
There's a JavaScript method called getMinutes(); you can use to get only the minutes and compare.
Your code should look something like:
var received_time = "14:10:00".split(':');
var minute = '';
if(received_time.length === 3) {
minute = parseInt(received_time[1], 10);
}
$scope.given_time = minute;
var the_time = new Date();
$scope.current_time = the_time.getMinutes();
And you now can do your thing:
if ($scope.given_time - $scope.current_time < 45 minutes) {
// do something
}
Using a library like moment.js you can simply diff the two times.
var $log = $("#log");
/* Difference between just times */
$log.append("Difference between times\n");
var givenTime = moment("14:10:00", "HH:mm:ss");
var minutesPassed = moment("14:30:00", "HH:mm:ss").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
/* Better: Difference between times that have dates attached to them and cross a day boundary. */
$log.append("\n\nDifference between dates with times\n");
givenTime = moment("2015-12-03 23:33:00");
minutesPassed = moment("2015-12-04 00:14:00").diff(givenTime, "minutes");
$log.append("Minutes passed: " + minutesPassed + "\n");
if (minutesPassed < 45) {
$log.append(minutesPassed + " minutes have elapsed. Event Triggered." + "\n");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://momentjs.com/downloads/moment.js"></script>
<p>Results:</p>
<hr>
<pre id="log"></pre>
<hr>
Caveat: If the given time is yesterday such as 11:30pm and the current time is 12:10am then you will get the wrong result. You'd want to use a date with the time if this type of thing is an issue for your use case.
The moment.js documentation
http://momentjs.com/docs/
Angular directive for moment documentation
https://github.com/urish/angular-moment/blob/master/README.md
I get a variable string like so:
8:45 am
And want, if it is pm, to convert it to 24 hour time. So that I can then drop the am/pm and use it with something else.
I can drop the am/pm quite easily like this:
function replaceEnds(string) {
string = string.replace("am", "");
string = string.replace("pm", "");
return string;
}
But of course if I do that, I don't know if the string is am or pm, so I don't know to add 12 hours on to the string to make it 24 hour.
Anyone know how I could resolve this? I absolutely cannot change the input that I get of the variable, it'll always be the hour (in 12 hour time), minutes, and am or pm.
Using moment.js:
moment(string, 'h:mm a').format('H:mm');
If you want to do it manually, this would be my solution:
function to24Hour(str) {
var tokens = /([10]?\d):([0-5]\d) ([ap]m)/i.exec(str);
if (tokens == null) { return null; }
if (tokens[3].toLowerCase() === 'pm' && tokens[1] !== '12') {
tokens[1] = '' + (12 + (+tokens[1]));
} else if (tokens[3].toLowerCase() === 'am' && tokens[1] === '12') {
tokens[1] = '00';
}
return tokens[1] + ':' + tokens[2];
}
The manual solution is harder to understand, is less flexible, is missing some error checking and needs unit tests. In general, you should usually prefer a well-tested popular library's solution, rather than your own (if a well-tested library is available).
Without using any additional JavaScript libraries:
/**
* #var amPmString - Time component (e.g. "8:45 PM")
* #returns - 24 hour time string
*/
function getTwentyFourHourTime(amPmString) {
var d = new Date("1/1/2013 " + amPmString);
return d.getHours() + ':' + d.getMinutes();
}
So for example:
getTwentyFourHourTime("8:45 PM"); // "20:45"
getTwentyFourHourTime("8:45 AM"); // "8:45"
In case you're looking for a solution that converts ANY FORMAT to 24 hours HH:MM correctly.
function get24hTime(str){
str = String(str).toLowerCase().replace(/\s/g, '');
var has_am = str.indexOf('am') >= 0;
var has_pm = str.indexOf('pm') >= 0;
// first strip off the am/pm, leave it either hour or hour:minute
str = str.replace('am', '').replace('pm', '');
// if hour, convert to hour:00
if (str.indexOf(':') < 0) str = str + ':00';
// now it's hour:minute
// we add am/pm back if striped out before
if (has_am) str += ' am';
if (has_pm) str += ' pm';
// now its either hour:minute, or hour:minute am/pm
// put it in a date object, it will convert to 24 hours format for us
var d = new Date("1/1/2011 " + str);
// make hours and minutes double digits
var doubleDigits = function(n){
return (parseInt(n) < 10) ? "0" + n : String(n);
};
return doubleDigits(d.getHours()) + ':' + doubleDigits(d.getMinutes());
}
console.log(get24hTime('6')); // 06:00
console.log(get24hTime('6am')); // 06:00
console.log(get24hTime('6pm')); // 18:00
console.log(get24hTime('6:11pm')); // 18:11
console.log(get24hTime('6:11')); // 06:11
console.log(get24hTime('18')); // 18:00
console.log(get24hTime('18:11')); // 18:11
I've use something similar to this
//time is an array of [hh] & [mm am/pm] (you can get this by time = time.split(":");
function MilitaryTime(time){
if(time[1].indexOf("AM")!=-1){
//its in the morning, so leave as is
return time;
}else if(time[0]!="12"){
//If it is beyond 12 o clock in the after noon, add twelve for military time.
time[0]=String(parseInt(time[0])+12);
return time;
}
else{
return time;
}
}
Once you get your time returned, you can alter the text in any way you want.