javascript conversion of yyyy-mm-dd hh:mm:ss aa help - javascript

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

Related

Convert string "15:00" to Time Format "3:00 pm" in node js

Please this "15:00" is coming to me as string.
I want convert it into 3:00 pm; means I want to convert it from GMT to EST.
Please tell me how to do it by inbuilt function or by creating some own function?
I wrote a function which could fit your needs:
function convertTime(time){
var arr = time.split(':'); //splits the string
var hours = Number(arr[0]);
var minutes = Number(arr[1]);
var AMPM = "";
if(hours>=12 && hours != 24){ //checks if time is after 12 pm and isn't midnight
hours = hours-12;
AMPM = " pm";
}else if(hours<12){//checks if time is before 12 pm
AMPM = " am";
}
if(hours==24){//special case if it is midnight with 24
hours = hours - 12;
AMPM = " am"
}
if(hours==0){//special case if it is midnight with 0
hours = hours + 12;
}
//converts the Numbers back to a string
var sHours = hours.toString();
var sMinutes = minutes.toString();
if(hours<10){//checks if the hours is 2 places long and adds a 0 if true
sHours = "0" + sHours;
}
if(minutes<10){//checks if the minutes is 2 places long and adds a 0 if true
sMinutes = "0" + sMinutes;
}
var result = sHours + ":" + sMinutes + AMPM; //sets string back together
return result;
}
https://jsfiddle.net/b059upu8/

How to convert string to Time with javascript [duplicate]

Please see the below code;
var d = new Date();
var s = "01.00 AM";
d.setTime(s);
I know this code is wrong. Please give me the correct way to set the time. I have 12 hour time in string format in my hand.
The time will vary. Cannot know what will be the time earlier. Also it is 12 hour time. So it will be AM or PM
You can parse the time with a regex, and set the hours and minutes accordingly:
http://jsfiddle.net/54VkC/1/
var d = new Date(),
s = "01.25 PM",
parts = s.match(/(\d+)\.(\d+) (\w+)/),
hours = /am/i.test(parts[3]) ? parseInt(parts[1], 10) : parseInt(parts[1], 10) + 12,
minutes = parseInt(parts[2], 10);
d.setHours(hours);
d.setMinutes(minutes);
alert(d);
Edit 1:
As jaisonDavis pointed out, the original code will not work for AM or PM for 12.XX, which was an oversight since I never use 12-hour format myself, thinking it started at 00.00 which was wrong.
The corrected code which handles these cases can be seen here:
http://jsfiddle.net/54VkC/93/
var test, parts, hours, minutes, date,
d = (new Date()).getTime(),
tests = ['01.25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
i = tests.length,
timeReg = /(\d+)\.(\d+) (\w+)/;
for(; i-- > 0;) {
test = tests[i];
parts = test.match(timeReg);
hours = /am/i.test(parts[3]) ?
function(am) {return am < 12 ? am : 0}(parseInt(parts[1], 10)) :
function(pm) {return pm < 12 ? pm + 12 : 12}(parseInt(parts[1], 10));
minutes = parseInt(parts[2], 10);
date = new Date(d);
date.setHours(hours);
date.setMinutes(minutes);
console.log(test + ' => ' + date);
}
I'm late to the party, but I thought I'd share a funtion that doesn't use regex:
function setDateTime(date, time) {
var index = time.indexOf("."); // replace with ":" for differently displayed time.
var index2 = time.indexOf(" ");
var hours = time.substring(0, index);
var minutes = time.substring(index + 1, index2);
var mer = time.substring(index2 + 1, time.length);
if (mer == "PM"){
hours = hours + 12;
}
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds("00");
return date;
}
Using moment.js will be the easy solution.
const fullDate = new Date();
// fullDate = Tue Dec 12 2017 11:18:30 GMT+0530 (IST) {}
const time = '01.00 AM';
const d = moment(fullDate).format('L'); // d = "12/12/2017"
const date = moment(d +' '+ time).format();
// date = "2017-12-12T01:00:00+05:30"
If you want convert moment date to js date
const jsDate = moment(date).toDate();
function getCurrentDate() {
var lDate = new Date();
var lDay = lDate.getDate();
var lMonth = lDate.getMonth() + 1;
var lYear = lDate.getFullYear();
if (lDay < 10) {
lDay = '0' + lDay
}
if (lMonth < 10) {
lMonth = '0' + lMonth
}
mCurrentDate = lYear + "-" + lMonth + "-" + lDay + "T00:00:00+05:30";
}
I added a few things as an improvement to the accepted answer by #thebreiflabb to suit my use case and thought i'd share.
if the regex is changed to timeReg = /(\d+)[\.|:](\d+)\s?(\w+)/;,
it'll handle a few other common cases.
namely:
using a colon instead of decimal point between hours and minutes
allowing am/pm to immediately follow the time with no space
also, setting the seconds to 0 (since that was my main use case)
the resulting code would be:
var test, parts, hours, minutes, date,
d = (new Date()).getTime(),
tests = ['01.25 PM', '01:25pm', '1:25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
i = tests.length,
timeReg = /(\d+)[\.|:](\d+)\s?(\w+)/;
for(; i-- > 0;) {
test = tests[i];
parts = test.match(timeReg);
hours = /am/i.test(parts[3]) ?
function(am) {return am < 12 ? am : 0}(parseInt(parts[1], 10)) :
function(pm) {return pm < 12 ? pm + 12 : 12}(parseInt(parts[1], 10));
minutes = parseInt(parts[2], 10);
date = new Date(d);
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds(0);
console.log(test + ' => ' + date);
}

Change GMT time format to 24 hours javascript

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.

How to let the return Json(datetime) return millisecondes according to the UTC?

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)"

Javascript set time string to date object

Please see the below code;
var d = new Date();
var s = "01.00 AM";
d.setTime(s);
I know this code is wrong. Please give me the correct way to set the time. I have 12 hour time in string format in my hand.
The time will vary. Cannot know what will be the time earlier. Also it is 12 hour time. So it will be AM or PM
You can parse the time with a regex, and set the hours and minutes accordingly:
http://jsfiddle.net/54VkC/1/
var d = new Date(),
s = "01.25 PM",
parts = s.match(/(\d+)\.(\d+) (\w+)/),
hours = /am/i.test(parts[3]) ? parseInt(parts[1], 10) : parseInt(parts[1], 10) + 12,
minutes = parseInt(parts[2], 10);
d.setHours(hours);
d.setMinutes(minutes);
alert(d);
Edit 1:
As jaisonDavis pointed out, the original code will not work for AM or PM for 12.XX, which was an oversight since I never use 12-hour format myself, thinking it started at 00.00 which was wrong.
The corrected code which handles these cases can be seen here:
http://jsfiddle.net/54VkC/93/
var test, parts, hours, minutes, date,
d = (new Date()).getTime(),
tests = ['01.25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
i = tests.length,
timeReg = /(\d+)\.(\d+) (\w+)/;
for(; i-- > 0;) {
test = tests[i];
parts = test.match(timeReg);
hours = /am/i.test(parts[3]) ?
function(am) {return am < 12 ? am : 0}(parseInt(parts[1], 10)) :
function(pm) {return pm < 12 ? pm + 12 : 12}(parseInt(parts[1], 10));
minutes = parseInt(parts[2], 10);
date = new Date(d);
date.setHours(hours);
date.setMinutes(minutes);
console.log(test + ' => ' + date);
}
I'm late to the party, but I thought I'd share a funtion that doesn't use regex:
function setDateTime(date, time) {
var index = time.indexOf("."); // replace with ":" for differently displayed time.
var index2 = time.indexOf(" ");
var hours = time.substring(0, index);
var minutes = time.substring(index + 1, index2);
var mer = time.substring(index2 + 1, time.length);
if (mer == "PM"){
hours = hours + 12;
}
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds("00");
return date;
}
Using moment.js will be the easy solution.
const fullDate = new Date();
// fullDate = Tue Dec 12 2017 11:18:30 GMT+0530 (IST) {}
const time = '01.00 AM';
const d = moment(fullDate).format('L'); // d = "12/12/2017"
const date = moment(d +' '+ time).format();
// date = "2017-12-12T01:00:00+05:30"
If you want convert moment date to js date
const jsDate = moment(date).toDate();
function getCurrentDate() {
var lDate = new Date();
var lDay = lDate.getDate();
var lMonth = lDate.getMonth() + 1;
var lYear = lDate.getFullYear();
if (lDay < 10) {
lDay = '0' + lDay
}
if (lMonth < 10) {
lMonth = '0' + lMonth
}
mCurrentDate = lYear + "-" + lMonth + "-" + lDay + "T00:00:00+05:30";
}
I added a few things as an improvement to the accepted answer by #thebreiflabb to suit my use case and thought i'd share.
if the regex is changed to timeReg = /(\d+)[\.|:](\d+)\s?(\w+)/;,
it'll handle a few other common cases.
namely:
using a colon instead of decimal point between hours and minutes
allowing am/pm to immediately follow the time with no space
also, setting the seconds to 0 (since that was my main use case)
the resulting code would be:
var test, parts, hours, minutes, date,
d = (new Date()).getTime(),
tests = ['01.25 PM', '01:25pm', '1:25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
i = tests.length,
timeReg = /(\d+)[\.|:](\d+)\s?(\w+)/;
for(; i-- > 0;) {
test = tests[i];
parts = test.match(timeReg);
hours = /am/i.test(parts[3]) ?
function(am) {return am < 12 ? am : 0}(parseInt(parts[1], 10)) :
function(pm) {return pm < 12 ? pm + 12 : 12}(parseInt(parts[1], 10));
minutes = parseInt(parts[2], 10);
date = new Date(d);
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds(0);
console.log(test + ' => ' + date);
}

Categories

Resources