How to show Only UAE Standard Time, Month, year in All Country - javascript

i'm use this code but i don't no how can show only uae standard time in all country.
<html>
<head></head>
<body>
<script>
var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var dayarray=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday",
"Friday","Saturday")
var montharray=new Array("January","February","March","April","May","June",
"July","August","September","October","November","December")
document.write(dayarray[day]+", "+montharray[month]+" "+daym+", "+year)
</script>
</body>
</html>
this is my code please suggest me right answer thanks.
see image for detail

try this in PHP, use date_default_timezone_set function, it's easy and simple
<?php
date_default_timezone_set('Asia/Dubai');
echo "The time is " . date('d-m-Y H:i:s');
?>
if you want to use in java script than try this
<script>
var d = new Date();
var localTime = d.getTime();
var localOffset = d.getTimezoneOffset() * 60000;
var utc = localTime + localOffset;
var offset = 4; //UTC of Dubai is +04.00
var dubai = utc + (3600000*offset);
var nd = new Date(dubai);
alert("Dubai time is " + nd.toLocaleString() + "<br>");
</script>

To get the local time of UAE you can try this code:
var d = new Date();
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var uaeDate = new Date(utc + (3600000*4)); // 4 is the offset of UAE
you can search offset of any region on google. Further you can parse date in any format.
Check this link.. There are many alternatives in this post for converting date to any timezone. check and see what works best for you...
Convert date to another timezone in JavaScript

Even though the UAE has a single timezone and no daylight savings time, so tricks involving adding a UTC offset can work, it is probably better to use more generic solutions.
You should probably use moment.js for generic date manipulation and formatting and its companion moment timezone for any timezone-related tasks.

Related

Using momentjs how to get today's midday

I need to get today's midday.
Please don't confuse the post with another StackOverflow post which says "How to get last midday in moments" which is unanswered and want to get the last date.
I want to get the current date not last
For example:
If today is 2020-05-12T22:00:00 should return 2020-05-12T12:00:00 and that's too in the same time zone.
I'm looking for something preexisting function in the moment if it exists.
Is there any method example: moment().someFunction(12, 'd').
Thanks in advance.
Try using moment-timezone to specify the timezone . Get the start of the day and then add 12 hours to it to give you the desired format
console.log(
moment("2020-05-12T22:00:00")
.tz("America/Los_Angeles")
.startOf("day")
.hour(12)
.minute(0)
.format()
);
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>
Get the start of the current day and add 12 hours in it .
var now = moment()
var startdate =now.startOf('day');
var midday = startdate.add(moment.duration(12, 'hours'));
console.log(midday.toString());
If you want to get the midday in any way you can do it like this. I didn't use moment.js in this example.
function getMidDate(date){
var dateParts = date.toLocaleString().split(":");
var hour = dateParts[0].replace(dateParts[0].split(" ")[1],"12");
var min = dateParts[1].replace(dateParts[1],"00")
var sec = dateParts[2].replace(dateParts[2],"00");
var middateString = hour + ":" + min + ":" + sec + "+0000";
var midDate = new Date(Date.parse(middateString));
return midDate;
}
var date = new Date();
console.log(getMidDate(date));

Setting timezone for running clock in JavaScript

Good days guys. I have this nice and clean code for a running clock.
<script type="text/javascript">
function DisplayTime(){
if (!document.all && !document.getElementById)
return
timeElement=document.getElementById? document.getElementById("curTime"): document.all.tick2
var CurrentDate=new Date()
var hours=CurrentDate.getHours()
var minutes=CurrentDate.getMinutes()
var seconds=CurrentDate.getSeconds()
var DayNight="PM"
if (hours<12) DayNight="AM";
if (hours>12) hours=hours-12;
if (hours==0) hours=12;
if (minutes<=9) minutes="0"+minutes;
if (seconds<=9) seconds="0"+seconds;
var currentTime=hours+":"+minutes+":"+seconds+" "+DayNight;
timeElement.innerHTML="<font style='font-family:Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&subset=latin,cyrillic-ext,latin-extfont-size:14px;color:#fff;'>"+currentTime+"</b>"
setTimeout("DisplayTime()",1000)
}
window.onload=DisplayTime
</script>
My only problem is it's based the system time. How can I set the timezone so that it will display the correct time based on the timezone specified?
There's nothing built into the JavaScript Date object that handles any timezones other than local (system) time and UTC.
You can do it by giving your Date instance the wrong time, using the delta between one of those timezones (local or UTC) and the time zone you want to use. It's easier if you use UTC.
So for instance, say we want our time in GMT+01:00:
var dt = new Date();
dt.setTime(dt.getTime() + (60 * 60 * 1000));
// ^^^^^^^^^^^^^^---- one hour in milliseconds,
// which is our offset from UTC/GMT
var hours = dt.getUTCHours(); // Use UTC methods to get time
var minutes = dt.getUTCMinutes();
var seconds = dt.getUTCSeconds();
Time stuff, particularly with timezones, is hard. You might look at using a library for it, although for just this sort of clock that would be overkill. One good library is MomentJS (which has a timezone add-on).
You can use getTimezoneOffset method of the Date object. It gives you the timezone offset, according to your timezone in minutes.
So in order to get the current time in UTC (+0 timezone) you can do something of the sort:
var tzOffset = CurrentDate.getTimezoneOffset();
// some timezones are not set hours, so we must calculate the minutes
var minutesOffset = parseInt(tzOffset%60,10);
// the offset hours for the timezone
var hoursOffset = parseInt(tzOffset/60, 10);
Then you need to do some math in your code to account for the offset:
var hours = CurrentDate.getHours() + hoursOffset;
var minutes = CurrentDate.getMinutes() + minutesOffset;
This would account for your timezone. If you want to calculate another timezone, that you specify, change the tzOffset above to show your timezone.
var tzOffset = CurrentDate.getTimezoneOffset() + TIMEZONE_HOURS*60;
TIMEZONE_HOURS is the timezone in hours you want, e.g. if you want UTC+3, you must set TIMEZONE_HOURS to 3.
As a whole timezones are a bit complicated task because they change a lot and there are some caveats with them. If you want to dwell more into this, check this answer in another question on SO
I have implemented your working code by adding one more function to obtain what you want. See this will help
function DisplayTime(timeZoneOffsetminutes){
if (!document.all && !document.getElementById)
return
timeElement=document.getElementById? document.getElementById("curTime"): document.all.tick2
var requiredDate=getTimeZoneTimeObj(timeZoneOffsetminutes)
var hours=requiredDate.h;
var minutes=requiredDate.m;
var seconds=requiredDate.s;
var DayNight="PM";
if (hours<12) DayNight="AM";
if (hours>12) hours=hours-12;
if (hours==0) hours=12;
if (minutes<=9) minutes="0"+minutes;
if (seconds<=9) seconds="0"+seconds;
var currentTime=hours+":"+minutes+":"+seconds+" "+DayNight;
timeElement.innerHTML="<font style='font-family:Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&subset=latin,cyrillic-ext,latin-extfont-size:14px;color:#fff;'>"+currentTime+"</b>"
setTimeout("DisplayTime(-330)",1000)
}
window.onload=DisplayTime(-330);
function getTimeZoneTimeObj(timeZoneOffsetminutes){
var localdate = new Date()
var timeZoneDate = new Date(localdate.getTime() + ((localdate.getTimezoneOffset()- timeZoneOffsetminutes)*60*1000));
return {'h':timeZoneDate.getHours(),'m':timeZoneDate.getMinutes(),'s':timeZoneDate.getSeconds()};
}
#curTime{
background-color:#000;
}
<div id="curTime"></div>
visit this link as a reference
example:
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
You can try using moment.js
It is very nice library which handles timezones too.

How to get the Australian Time Zone using Javascript? (Not JQuery)

I am trying to help a friend to get the Australian Time Zone for the University Assignment and finding difficulty.
Could someone point us in the right direction?
Thank you!
<script>
function Timezone() {
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
document.getElementById("add").innerHTML = currentTimeZoneOffsetInHours;
}
</script>
<p id="add"></p>
You simply use
let AuDate = new Date().toLocaleString("en-US", {timeZone: "Australia/Sydney"});
By looking at your code, looks like you are trying to get the current date and time of an Australian timezone. Lets say you want Australian Eastern Standard Time (AEST) and you want the date displayed how they would in Australia DD-MM-YYYY then do the following:
var timestamp_UTC = new Date();
var readable_timestamp_AEST = timestamp_UTC.toLocaleDateString("en-AU", {timeZone: "Australia/Sydney"}).replace(/\//g, "-") + ' ' + somestamp.toLocaleTimeString("en-AU", {timeZone: "Australia/Sydney"});
"en-AU" is the locales argument which tells the toLocalDateString to display the date as DD-MM-YYYY and the second argument is for options (timeZone is just one such possible option). Info about toLocalDateString function can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
Here is some information about the Date() function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Hope this clears up a few things around getting times and dates from the Date() function.
I think i understand what you mean. But before that i'd like to make 2 points:
1: The Timezone() function should be called somewhere.
<script>
function Timezone() {
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
document.getElementById("add").innerHTML = currentTimeZoneOffsetInHours;
}
Timezone();
</script>
2: The convention usually is that methods start with a lower case letter. Maybe updateTimezone() would be more appropriate.
Your question can be interpreted in 2 ways now:
you want your timezone's offset in hours and for this the code above should work. getTimezoneOffset() is the way to go.
you want a human readable name of your timezone, as you can see on my site currentmillis.com (in my case it says GTB Summer). You can look in my source code to see how i achieve this:
var s = date.toString();
var iOfP = s.indexOf('('); // index of parenthesis
if (iOfP < 0) {
s = s.substring(s.lastIndexOf(' ') + 1);
} else {
s = s.substring(iOfP+1, s.length-1);
}
if (s.length > 4 && s.lastIndexOf(" Time") == s.length-5){
s = s.substring(0, s.length-5);
}
timezoneM.innerHTML = s;
This works because when you call toString() on the date the result should contain the full name of your timezone: w3schools.com/jsref/jsref_tostring_date.asp

Javascript running Date Time return value is working in chrome but not in Internet explorer

I have a javascript function to run time in different manner.
Its working well in Chrome browser but its not showing proper value in Internet Explorer.
In Chrome:
13-Dec-2011 13:14:19
In IE8:
0NaN-undefined-NaN 0NaN:0NaN:0NaN
You can view this from this page link from both the browsers. Also look at the source code of page
http://chemfluence.org.in/monetarist/sample.php
My Code:
<div id="txt" title="Industries will generate products on every 3 Virtual days.
12 Virtual Days = 1 Real day. dd-Mon-yyyy HH:MM:SS ."></div>
Javascript
<script type='text/javascript'>//<![CDATA[
var virtualOrigin = Date.parse("2012-02-27T00:00:00"),
game_start_realdate=Date.parse("2013-01-27T12:00:00"),
realOrigin = Date.now(),
factor = 12;
function getVirtual(time) {
return new Date( virtualOrigin + ((time - realOrigin) * factor) +(realOrigin-game_start_realdate)*factor);
}
function pad2(num) {
return ("0"+num).substr(-2);
}
function format(time) {
var month=new Array();
month[0]="Jan";
month[1]="Feb";
month[2]="Mar";
month[3]="Apr";
month[4]="May";
month[5]="Jun";
month[6]="Jul";
month[7]="Aug";
month[8]="Sep";
month[9]="Oct";
month[10]="Nov";
month[11]="Dec";
return pad2(time.getDate())
+ "-" + month[time.getMonth()]
+ "-" + time.getFullYear()
+ " " + pad2(time.getHours())
+ ":" + pad2(time.getMinutes())
+ ":" + pad2(time.getSeconds());
}
function startTime() {
var now = new Date();
var display = getVirtual(now);
output.innerText = format(display);
setTimeout(startTime, 1000/factor - (now.getMilliseconds() % (1000/factor)));
}
var output = document.getElementById("txt");
startTime();
</script>
I need the above Javascript to be modified to work in Internet Explore and Chrome/Firefox;
Please give me modified code;
Try using moment.js. it is cross browser and can make doing dates in javascript much less of a pain. The documentation is very thorough. http://momentjs.com/docs/
You can format your date with as little as:
var day = moment("12-25-1995", "MM-DD-YYYY");
http://momentjs.com/docs/#/parsing/string-format/
UPDATE
Here is an example of it's full usage.
var mysql_date = '2013-01-25 10:00:00'; // Date from MySQL database
/**
* #param string mysql_data Date string
* #param string format Format in which mysql_data is set
*/
var date = moment(mysql_date , 'YYYY-MM-DD HH:mm:ss'); // new moment.js object.
// To display the date in a different format use:
var date_format1 = date.format('MMM, Do'); // Format here would be Jan, 25th
var date_format2 = date.format('MMMM, Do, YYYY'); // January, 25th, 2013
console.log(date_format1, date_format2);
You can change the format when ever you want. You don't need to recreate it again.
Take a custom parse function to be sure that you can parse that date format whatever the browser is:
function parse(datestring){
var timearray = datestring.split(/[\-T\:]/g)
return +new Date(+timearray[0],timearray[1]-1,+timearray[2],+timearray[3],+timearray[4],+timearray[5])
}
And fix the pad2 function to work with IE8 by not using substr with a negative value:
function pad2(num) {
return ("0"+num).slice(-2);
}
That should do it.

how to format time with jquery/javascript

I have a JSON feed that drupal spits out time in this format: 2010-12-16T04:41:35Z
How do I go about formating it to X minutes/hours ago?
Take a look at the timeago jQuery plugin which can be used programtically like
var t = jQuery.timeago("2010-12-16T04:41:35Z");
or on HTML elements like
<time class="timeago" datetime="2008-07-17T09:24:17Z">July 17, 2008</time>
<script type="javascript">
jQuery(document).ready(function() {
jQuery("time.timeago").timeago();
});
</script>
I think something on this page will help you. There's a couple formatting jQuery plugins toward the bottom. Good luck!
Here is a highly relevant Stack Overflow post: How can I convert string to datetime with format specification in JavaScript?
You can use regexp object in JS to build your own regular expression, separate hours-minutes-secs from the original string and then do whatever you want.
Tip: actual_date - your original string time
does the 04:41:35 part is correct? or do you need like to take into consideration time zones and stuff?
because basically this can work:
var str = "2010-12-16T04:41:35Z"
var arr = str.split("T")
arr[0] = arr[0].split("-")
arr[1] = (arr[1].replace(/Z/ig,"")).split(":")
var year = arr[0][0]
var month = parseInt(arr[0][1],10)-1
var day = arr[0][2]
var hours = arr[1][0]
var minutes = arr[1][1]
var seconds = arr[1][2]
var d = new Date(year, month, day, hours, minutes, seconds, 0);
var now = (new Date())
var diffMS = now.getTime() - d.getTime()
//alert ("difference in milliseconds: " + diffMS)
var hoursago = diffMS/1000/60
var ANDminutes = (diffMS - Math.floor(hoursago) * 1000*60)/1000
alert (Math.floor(hoursago) + " hours and " + ANDminutes + " minutes ago")
<shameless_plug>
Here's a library which give you a humanized time difference.
https://github.com/layam/js_humanized_time_span
The output is completely customizable, allowing you to set different output formats for various time bands; So you could have:
'10 seconds ago'
or
'3 days and 2 hours ago'
you can even set custom time units.
Additionally it's native JS and so doesn't rely on any framework.
</shameless_plug>

Categories

Resources