I have a GMT time format and I changed it to my local browser time by using:
var newDate = new Date(GMTFromat);
mytime= newDate.toLocaleString();
The output is:
3/12/2010 1:02:00 PM
Now I want to change 12 hours to 24 hours format in javascript.
Example:
3/12/2010 13:02:00
Any suggestion?
Thanks
enter code hereIts a copy of SO link
Code from the above link:
function to24Hour(str) {
var tokens = /([10]?\d):([0-5]\d):([0-5]\d) ([ap]m)/i.exec(str);
if (tokens == null) { return null; }
if (tokens[4].toLowerCase() === 'pm' && tokens[1] !== '12') {
tokens[1] = '' + (12 + (+tokens[1]));
} else if (tokens[4].toLowerCase() === 'am' && tokens[1] === '12') {
tokens[1] = '00';
}
return tokens[1] + ':' + tokens[2] + ":" + tokens[3];
}
Edit:
var date = "3/12/2010 8:45:59 AM";
var dateTime = date.split(" ");
var datePart = dateTime[0];
var timePart = dateTime[1] + " " + dateTime[2];
timePart = to24Hour(timePart);
var finalDate = datePart + timePart;
This can be done in any number of ways, but I wanted to do it using just the replace method. Here you go:
(new Date()).toLocaleString().replace(/(.+ )(\d+)(:.+)(\wM)/g, function replacer(match, p1, p2, p3, p4) {
return p1 + (p4 === "PM" ? (12 + Number(p2)) : p2) + p3;
});
DEMO
$(function(){
alert(
moment("3/12/2010 1:02:00 PM", "M/DD/YYYY hh:mm:ss A").
format("M/DD/YYYY HH:mm:ss")
);
});
fiddle
Here small hh for 12-clock system and HH for 24 clock system.
Related
This question already has answers here:
How to ISO 8601 format a Date with Timezone Offset in JavaScript?
(21 answers)
Closed 6 years ago.
In my database I must put a date time in ISO format with time zone. For example I have the following entry column:
17/02/2016 22:00:00 +01:00
I have a web service that accept a date (in JSON object) like this:
{
//...
"Start": "2016-02-17T22:00:00+01:00"
//...
}
Now in my javascript code i've tried:
var today = new Date();
var dateString = today.toISOString();
But the output of dateString is:
"2016-03-05T12:10:32.537Z"
How can I get a string like this:
"2016-03-05T13:10:32.537+01:00"
Thanks
I believe you can't obtain a local ISO 8601 format directly from a Date function. toISOString() gives you the time in UTC / GMT: 2016-03-05T12:10:32.537Z (that's what the Z in the end is for, it means UTC)
This is how you can do it by composing the string yourself:
var date = new Date(); // this is your input date
var offsetHours = -date.getTimezoneOffset() / 60;
var offsetMinutesForDisplay = Math.abs(-date.getTimezoneOffset() % 60);
var offsetHoursForDisplay = Math.floor(offsetHours) + (offsetHours < 0 && offsetMinutesForDisplay != 0 ? 1 : 0);
var isoOffset = (offsetHours >= 0 ? ("+" + fillDigit(offsetHoursForDisplay, true)) : fillDigit(offsetHoursForDisplay, true)) + ':' + fillDigit(offsetMinutesForDisplay, true);
document.getElementById('myDiv').innerHTML = date.getFullYear() + '-' + fillDigit(date.getMonth() + 1, true) + '-' + fillDigit(date.getDate(), true) + 'T' + fillDigit(date.getHours(), true) + ':' + fillDigit(date.getMinutes(), true) + ':' + fillDigit(date.getSeconds(), true) + isoOffset;
function fillDigit(value, withDigit) { // we want to display 04:00 instead of 4:00
if (value >= 0 && value < 10) {
return (withDigit ? "0" : " ") + value;
}
if (value > -10 && value < 0) {
return '-' + (withDigit ? "0" : " ") + (-value);
}
return value;
}
<div id='myDiv'></div>
You can check out http://currentmillis.com/?now for Javascript that will get you multiple formats
If you want a custom format you need format the date by yourself using Date object methods like:
date = new Date();
hour= date.getHours();
min= date.getMinutes();
sec= date.getSeconds();
time= hour+':'+min+':'+sec;
console.log(time)
This can be encapsulated in a function or in a object method for convenience.
In my program i need to alert current date with time in specific format(2015-11-18 12:23:00) so i am write like this
var date = new Date();
alert(date);
but the result is Wed Nov 18 2015 12:24:28 GMT+0530 (India Standard Time).
and also i am try like this
<script>
var d = new Date();
var c = new Date();
alert(formatDate(c));
alert(formatDate(d));
function formatDate(d)
{
var month = d.getMonth();
var day = d.getDate();
var hours = d.getHours();
var minutes = d.getMinutes();
month = month + 1;
month = month + "";
if (month.length == 1)
{
month = "0" + month;
}
day = day + "";
if (day.length == 1)
{
day = "0" + day;
}
hour = hour + "";
if (hour.length == 1)
{
hour = "0" + hour;
}
minute = minute + "";
if (minute.length == 1)
{
minute = "0" + minute;
}
return d.getFullYear()+month + '' + day + ''+ hour + '' + minute + '';
}</script>
it is also not working properly.
how can i do this in javascript and also i need to passed the veriable to database in another php file. please help me how can i do this
I think this below code are helpful us.
function getDateTimeFormate () {
now = new Date();
year = "" + now.getFullYear();
month = "" + (now.getMonth() + 1); if (month.length == 1) { month = "0" + month; }
day = "" + now.getDate(); if (day.length == 1) { day = "0" + day; }
hour = "" + now.getHours(); if (hour.length == 1) { hour = "0" + hour; }
minute = "" + now.getMinutes(); if (minute.length == 1) { minute = "0" + minute; }
second = "" + now.getSeconds(); if (second.length == 1) { second = "0" + second; }
return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}
To get date time formate like.
alert(getDateTimeFormate());
// example alert message: 2011-05-18 15:20:12
Try this..
<script>
var currentdate = new Date();
var datetime = currentdate.getFullYear() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getDate() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
alert(datetime);
</script>
Output:2015-11-18 12:46:52
Demo:http://js.do/code/73749
Please try the following code:
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
var d = new Date;
function formatDate(d){
dformat = [ (d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('-')+
' ' +
[ d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
return dformat;
}
alert(formatDate(d));
It will return : 11-18-2015 12:17:02. And to pass the value to a php code check this: How to pass JavaScript variables to PHP?
This might be useful
Date.prototype.yyyy = function() {
var yy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
var hh = this.getHours().toString();
var min = this.getMinutes().toString();
var ss = this.getSeconds().toString();
return yy +"-" +(mm[1]?mm:"0"+mm[0]) + "-" +(dd[1]?dd:"0"+dd[0])+" "+(hh[1]?hh:"0"+hh[0])+":"+(min[1]?min:"0"+min[0])+":"+(ss[1]?ss:"0"+ss[0]);
};
d = new Date();
d.yyyy();
From the below function you will get all the details you want to show use it according to your need
getMonth() - Returns a zero-based integer (0-11) representing the month of the year.
getDate() - Returns the day of the month (1-31).
getDay() - Returns the day of the week (0-6). 0 is Sunday, 6 is Saturday.
getHours() - Returns the hour of the day (0-23).
getMinutes() - Returns the minute (0-59).
getSeconds() - Returns the second (0-59).
getMilliseconds() - Returns the milliseconds (0-999).
getTimezoneOffset() - Returns the number of minutes between the machine local time and UTC.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
var today = dd+'/'+mm+'/'+yyyy;
document.getElementById("DATE").value = today;
Use this code:
var sec = d.getSeconds();
return d.getFullYear()+'-'+month + '-' + day + ' '+ hour + ':' + minute + ':'+sec;
instead of:
return d.getFullYear()+month + '' + day + ''+ hour + '' + minute + '';
I have a function that retrieves event dates(json format) by ajax. My function should convert the date to a human friendly format. Everything is working but not perfectly. The problem is:
When the server date is
"21/06/2013 22h00" this function returns "22/06/2013 05h00"
"26/07/2013 18h30" this function returns "27/07/2013 01h30"
which is 6 hours of advance.
PS: between my country and the country where my server is located, there is a difference of exactly 6 hours..
Where do I have to put a UTC function?
what's realy wrong with my function?
Thank you
Here is the code:
var jsonifyMyDate = function (jsonDate) {
var parser = parseInt(jsonDate.substr(6));
if (parser > 0 && !isNaN(parser)) {
var newDate = new Date(parser),
_date = newDate.getDate(),
_month = newDate.getMonth() + 1,
_year = newDate.getFullYear(),
_hour = newDate.getHours(),
_minute = newDate.getMinutes();
var dateStr = (_date < 9 ? "0" : "") + _date;
dateStr += "/" + (_month < 9 ? "0" : "") + _month;
dateStr += "/" + _year;
dateStr += " "+(_hour < 9 ? "0" : "") + _hour + "h";
dateStr += (_minute < 9 ? "0" : "") + _minute;
/* + "-" + newDate.getSeconds() + "-" + newDate.getMilliseconds() + "";*/
return dateStr;
} else return "";
UPDATE: I can see the problem with my the server side parsing function within the ActionResult...
So, as I am using Asp.Net+MVC(C#), How to let the
return Json(datetime);
return UTC millisecondes instead of the server's one ?
Json formate is created based on UTC datetime.
After getting the datetime from ajax call, you have to convert this UTC datetime in to local datetime zone.
Ex:
var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
I have trouble using date in Javascript, in PHP you use something like date("Y-m-d H:i s") to retrieve the specific date and time, how can I achieve this in Javascript? the getMonth() method only returns 1 digit, I really need them to be in 2 digits
Since I made comments on almost all answers, I'd better post my suggestion
DEMO
function pad(num) { return ("0"+num).slice(-2); }
function getDisplayDate() {
var date = new Date();
return date.getFullYear()+
"-"+pad(date.getMonth()+1)+
"-"+pad(date.getDate())+
" "+pad(date.getHours())+
":"+pad(date.getMinutes())+
":"+pad(date.getSeconds());
}
setInterval(function() {
document.getElementById("time").innerHTML=getDisplayDate();
},500);
why dont you add 0 before when you get <10
Try this :
function dateToYMD(date) {
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d) + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
}
var d = new Date();
alert(dateToYMD(d));
This code is adjusted based on the pointers given by #mplungjan -- (credits to him please)
Also check out his solution, which is a better one for use with date digits.
var str = 10; // month-digit from getMonth()
function pad(val) {
return "0" + val;
}
var month = str < 10 ? pad(str) : str;
console.log(month);
you can year, minutes, etc from Date class. You can get 2 digits month using some trick like example below. e.g
Date.prototype.getLongMonth = function() {
var month = this.getMonth();
if (String(month).length == 1) month = '0'.concat(month);
return month;
}
var now = new Date();
var theDate = now.getFullYear() + '-' + now.getLongMonth() + '-' + now.getDate() + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
console.log(theDate); // result : 2013-02-17 12:41:2
can anybody spot any mistake in this function? .. This is a function which receives a string of type yyyy-mm-dd hh:mm:ss aa and converts to UTC and builds up a string yyyy-mm-dd hh:mm:ss.
function LocalTimetoUTC(localTime)
{
var time = localTime.split(" "); //Received :- yyyy-mm-dd hh:mm:ss aa
var yearday = time[0].split("-");
var dateTime = time[1].split(":");
var ampm = time[2];
var hours = 0;
var year = yearday[0];
var month = yearday[1]-1;
var day = yearday[2];
hours = dateTime[0];
var minutes = dateTime[1];
var seconds = dateTime[2];
/* We have to first convert it to 24 hour format
* 12:00:00 AM : 00:00:00
* 12:00:00 PM : 12:00:00
* Anytime other than 12
* 1:00:00 AM : 1:00:00
* 1:00:00 PM : 13:00:00
*/
if(ampm == "PM")
{
//If it is 12PM, adding 12 will create a problem
if(hours != 12)
{
hours +=12;
}
}
else //AM CASE
{
if(hours == 12)
{
hours = 00;
}
}
var now = new Date(year,month,day,hours,minutes,seconds);
var utcString = now.getUTCFullYear()+"-"
+(now.getUTCMonth()+1)+"-"+now.getUTCDate()+""
+now.getUTCHours()+":"+now.getUTCMinutes()+":"+now.getUTCSeconds();
return utcString;
}
Your primary problem is you are using strings in numeric operations. In addition your output formatting has some problems too. Here is an untested refactoring:-
function convertToUTCString(localTime)
{
var dateTimeComponents = localTime.split(" ");
var dateComponent = dateTimeComponents[0].split("-");
var timeComponent = dateTimeComponents[1].split(":");
var ampm = dateTimeComponents[2]
var dat = new Date(parseInt(dateComponent[0]),
parseInt(dateComponent[1]) -1,
parseInt(dateComponent[2]),
parseInt(timeComponent[0]) % 12,
parseInt(timeComponent[1]),
parseInt(timeComponent[2]) );
if (ampm == "PM") // do all locales use 'AM' / 'PM' ??
{
dat.setHours(dat.getHours() + 12);
}
function pad(val)
{
var s = val.toString();
return s.length < 2 ? "0" + s : s
}
return dat.getUTCFullYear() + "-" +
pad((dat.getUTCMonth() + 1 )) + "-" +
pad(dat.getUTCDate()) + " " +
pad(dat.getUTCHours()) + ":" +
pad(dat.getUTCMinutes()) + ":" +
pad(dat.getUTCSeconds());
}
Yyou should use Datejs for parsing dates