Change dates inside span to match user's timezone - javascript

I have this function:
function get_time_zone_offset() {
var current_date = new Date();
return -current_date.getTimezoneOffset() / 60;
}
I want a jQuery code to change every span which class is 'timeago' title value to its value plus the number the function above returns. For example:
Before:
<span class="timeago" title="7/4/2012 9:28:30 AM">7/4/2012 9:28:30 AM</span>
After:
<span class="timeago" title="7/4/2012 12:28:30 PM">7/4/2012 12:28:30 PM</span>

Assuming 7/4/2012 9:28:30 AM represents UTC, you can let the Date object do all the math:
function formatDate(d) {
var yy = d.getFullYear();
var mm = d.getMonth() + 1;
var dd = d.getDate();
var hh = d.getHours();
var ii = d.getMinutes();
var ss = d.getSeconds();
var ap;
if (hh < 12) {
if (hh === 0) {
hh = 12;
}
ap = "AM";
}
else {
if (hh > 12) {
hh -= 12;
}
ap = "PM";
}
return mm + "/" + dd + "/" + yy + " " + hh + ":" + ii + ":" + ss + " " + ap;
}
$("span.timeago").each(function() {
var dateInput = $(this).text();
var dateInUTC = new Date(dateInput + " +0000"); // note: +0000 is the key
var dateOutput = formatDate(dateInUTC);
$(this).attr("title", dateOutput).text(dateOutput);
});
This assumes that the date is parsable. Here is a demo.

It seems a simple loop like this should work:
$('span.timeago').each(function(index, elm) {
var newVal = $(elm).attr('title') * 1 + get_time_zone_offset(); // multiply by 1 to suppress string concatenation
$(elm).attr('title', newVal);
});

It's pretty straightforward by passing a function to .attr [docs]:
var offset = get_time_zone_offset();
$('span.timeago').attr('title', function(i, val) {
return +val + offset;
});
If you have to convert the value to a proper timestamp first, have a look at How to convert from date to unix_timestamp using javascript.
If you are using the Timeago plugin, note this remark:
Are you concerned about time zone support? Don't be. Timeago handles this too. As long as your timestamps are in ISO 8601 format and include a full time zone designator (±hhmm), everything should work out of the box regardless of the time zone that your visitors live in.
So you might not even have to do this conversion manually. Just add the proper timezone information to values.

Related

Converting string m/dd/yyyy HH:MM:SS to date dd-mm-yyyy in Javascript

I have a string that looks like '1/11/2018 12:00:00 AM' and I want to reformat it to dd-mm-yyyy.
Keep in mind that the month can be double digit sometimes.
You can use libraries like moment.js. Assuming either you do not want to use any external library or can not use it, then you can use following custom method:
function formatDate(dateStr) {
let date = new Date(dateStr);
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
return day + '-' + month + '-' + year;
}
console.log(formatDate('1/11/2018 12:00:00 AM'));
You can do somethink like this :
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
console.log(curr_date + "-" + curr_month + "-" + curr_year);
However best way is with Moment.js,where you can Parse, Validate, Manipulate, and Display dates in JavaScript.
example:
var date= moment("06/06/2015 11:11:11").format('DD-MMM-YYYY');
function convertDate(oldDate) {
var myDate = new Date(Date.parse(oldDate)); //String -> Timestamp -> Date object
var day = myDate.getDate(); //get day
var month = myDate.getMonth() + 1; //get month
var year = myDate.getFullYear(); //get Year (4 digits)
return pad(day,2) + "-" + pad(month, 2) + "-" + year; //pad is a function for adding leading zeros
}
function pad(num, size) { //function for adding leading zeros
var s = num + "";
while (s.length < size) s = "0" + s;
return s;
}
convertDate("1/11/2018 12:00:00 AM"); //11-01-2018
Demo here

If Date is empty format_date() returns NaN/NaN/NaN insted of no value

I am using jquery autocomplete onselect it is showing data in different text field. I am showing formatted date in #dob and #anniversery by using format_date() function
select: function(event, ui) {
$("#customerId").val(ui.item.id);
$("#customerName").val(ui.item.value);
var datefield = new Date(ui.item.dob);
$("#dob").val(format_date(datefield));
var datefield1 = new Date(ui.item.anni);
$("#anniversery").val(format_date(datefield1));
$("#address").val(ui.item.address);
$("#mobNo").val(ui.item.mobno);
},
});
function format_date(dt) {
alert(dt);
var dd = dt.getDate();
var mm = dt.getMonth() + 1; //January is 0!
var yyyy = dt.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
dt = mm + '/' + dd + '/' + yyyy;
return dt;
}
});
Above code is working properly if ui.item.dob and ui.item.anni is not null.
In case of null it is showing NaN/NaN/NaN
If date value is empty it should not show anything in textbox.
alert(dt) prints Invalide date.
How to resolve this.
You can check whether a Date instance is an invalid date by checking one of the properties for NaN:
function format_date(dt) {
if (isNaN(dt.getFullYear())) return "";
// ...
}
In your function, check that the Date object is okey using isNaN function. Also, there's an easier way of formating the date as you want, with out all the ifs:
function format_date(dt) {
if(isNaN(dt.getTime()) return "";
return dt.getFullYear + '/' + String('00' + (dt.getMonth() + 1)).slice(-2) + '-' + String('00' + dt.getDate()).slice(-2);
}
Also good to know is that initializing a Date object like var datefield = new Date(ui.item.dob); has a bit poor browser support (
A more safe way of doing it is to initialize the Date object without any proporties, var datefield = new Date(); and the using the Date set*() functions to set the time. A whole lot more code, but if you need it to work in old browsers...
Example
http://jsfiddle.net/HMb68/
var inDateTime = '2014-07-26 17:52:00',
inDateTimeSplit = inDateTime.split(' '),
inDateParts = inDateTimeSplit[0].split('-'),
inTimeParts = inDateTimeSplit[1].split(':'),
outDate = new Date;
outDate.setFullYear(parseInt(inDateParts[0], 10));
outDate.setMonth((parseInt(inDateParts[1], 10) - 1));
outDate.setDate(parseInt(inDateParts[2], 10));
outDate.setHours(parseInt(inTimeParts[0], 10));
outDate.setMinutes(parseInt(inTimeParts[1], 10));
outDate.setSeconds(parseInt(inTimeParts[2], 10));
outDate.setMilliseconds(0);
console.log(outDate);

Is there a reliable way to convert a naive UTC time stamp to local time with javascript?

Determining a user's timezone server side and converting from UTC has proven more trouble than its worth.
Is there a reliable way for javascript/jquery to determine the timezone of the user and apply the offset to a UTC datetime stamp (2012-08-25 10:59:56.511479) and output in my desired format (Aug 25 '12 - 10:59AM)?
What might the jquery code look like to say
// dom ready
$('span.localtime').each(function(e) {
// get stamp and apply conversion
});
.getTimezoneOffset() is available on the date object, and gives you the offset from UTC in minutes.
var offset = (new Date()).getTimezoneOffset();
// convert myUtcDate to a date in local time
myUtcDate.setMinutes(myUtcDate.getMinutes() + (offset*-1));
Thus:
$('.span.localtime').each(function() {
var myUtcDate = new Date($(this).html()); // assuming "2012-08-25 10:59:56.511479"
myUtcDate.setMinutes(myUtcDate.getMinutes() + (myUtcDate.getTimezoneOffset() * -1));
$(this).html(myUtcDate.toString());
});
Note that myUtcDate.toString() could be replaced with any date formatting you want. In your case, it might look like
$(this).html(formatDate(myUtcDate));
function formatDate(d) {
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var y = d.getFullYear().toString().slice(-2); // "12"
var m = months[d.getMonth()]; // "Aug"
var d = d.getDate(); // "25"
var ampm = 'AM';
var h = d.getHours();
if(h>=12) {
h -= 12;
ampm = 'PM';
}
if(h == 0)
h = 12;
var min = ("00" + d.getMinutes()).slice(-2);
return m + " " + d + " '" + y + " - " + h + ":" + min + ampm;
}
You might want to use a date format plugin for formatting dates in a neater more reliable manner.
Also, have a look at https://github.com/GregDThomas/jquery-localtime - it wraps all this up in a simple to use jQuery plugin.

Javascript: wrong date calculation

So I just have posted a question about this code (which was answered):
$(document).ready(Main);
function Main() {
ConfigDate();
}
function ConfigDate() {
var currentTime = new Date();
var dayofWeek = currentTime.getDay();
var daysSinceThursday = (dayofWeek + 3) % 7
var lastThursday = new Date(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
$("#last_thursday").text(yyyy + " / " + mm + " / " + dd);
}
The problem now is that the date that appears in my cell is 1969 / 12 / 31 (which isn't even a thursday).
Did I do something wrong while calculating last thursday date?
This is because .getDate() returns the day of the month. So you are building your date based on a serial number of something less than 30, which won't even set your seconds above 1.
Use .setDate() instead of building a new date:
date.setDate(date.getDate() - daysSinceThursday);
.setDate() will modify your existing date object, it doesn't return a new date.
You're trying to set a Date based only on the day of the month of the last Thursday. Try something like this:
var daysSinceThursday = (dayofWeek + 3) % 7;
var lastThursday = new Date(currentTime.getTime());
lastThursday.setDate(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
http://jsfiddle.net/rAuRF/3/

How to format a dateTime

Okay I have the following problem. I want to get the current dateTime and then want do check if a date that I enter is bigger than the current DateTime. The format of my dateTime should look like this.
03/11/2012 09:37 AM
Here is the function how I get the current DateTime.
function getCurrentDateTime()
{
var currentTime = new Date()
// Date
var month = currentTime.getMonth() + 1;
if (month < 10){
month = "0" + month;
}
var day = currentTime.getDate();
var year = currentTime.getFullYear();
// Time
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (minutes < 10){
minutes = "0" + minutes;
}
if(hours > 11){
var dateString = month + "/" + day + "/" + year + " " + hours + ":" + minutes + " " + "PM";
test = new Date(dateString);
return dateString ;
} else {
var dateString = month + "/" + day + "/" + year + " " + hours + ":" + minutes + " " + "AM";
return dateString;
}
}
As you can see how it gives back a string. But when I want to covert it to a date with this function. I get this format Fri May 11 2012 09:37:00 GMT+0200 (Romance Daylight Time)
date = new Date(dateString);
And with this I can't calculate.
Could anybody help me how I can get the current date in this format so that I can do the check?
Kind regards.
Javascript provides very limited functionality for working with dates out of the box. Use an external library like momentjs.
For example, your function would be reduced to
var stringDate = moment().format("DD/MM/YYYY HH:mm A");
And you could convert that and compare it to the current time with
var earlierDate = moment(stringDate, "DD/MM/YYYY HH:mm A");
if (earlierDate.valueOf() < moment().valueOf()) {
// earlier indeed
}
datejs is another lib for solving date-manipulation problems

Categories

Resources