JQuery date and time in mysql databse datetime format - javascript

I want to store my country date and time in JavaScript var variable using JQuery. That date and time should be in default mysql database datetime format. JQuery date and time should not be local date time and not for auto get timezone date time. That should be UTC +09:30 date and time in set.
PHP Code for that in mysql datetime format:
CONVERT_TZ(NOW(), 'UTC', '+09:30')
OR
Tell me how to convert JQuery NOW() date time data to mysql datetime format in PHP.
Final answer should be date and time in mysql datetime format and that should be in javascript var veritable or PHP veritable.

Javascript date and time will be in local timezone.
If you want to display the time just like mysql time, then you will have to convert the localtime to server timezone in javascript.
You can you date.getTimezoneOffset(), to get the offset between local time and utc, and then use this to convert locatime to utc+9:30
Edit
how to convert JQuery NOW() date time data to mysql datetime format in
PHP.
Final answer should be date and time in mysql datetime format and that
should be in javascript var veritable or PHP veritable.
Example to convert locatime to different timezone ( UTC + 9:30 )
var localDate = $.now();
localDate = new Date(localDate);
console.log("local datetime is ", printMysqlFormat(localDate));
var offset = localDate.getTimezoneOffset();
var offsetMilliseconds = offset * 60 * 1000;
var serverMilliseconds = localDate.getTime() + offsetMilliseconds + (570 * 60 * 1000)
var serverdate = new Date(serverMilliseconds);
console.log("localtime in server timezone is", printMysqlFormat(serverdate));
function printMysqlFormat(d) {
var day = d.getDate() + "";
var month = (d.getMonth() + 1) + "";
var year = d.getFullYear() + "";
var hour = d.getHours() + "";
var minutes = d.getMinutes() + "";
var seconds = d.getSeconds() + "";
day = day.length == 1 ? "0" + day : day;
month = month.length == 1 ? "0" + month : month;
hour = hour.length == 1 ? "0" + hour : hour;
minutes = minutes.length == 1 ? "0" + minutes : minutes;
seconds = seconds.length == 1 ? "0" + seconds : seconds;
return day + "-" + month + "-" + year + " " + hour + ":" + minutes + ":" + seconds;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

How to convert strings of the format "6 Dec, 2022 " to a date? [duplicate]

In BIRT, i have a column containing a datetime stored as a string. I need to convert these string to datetime format and put the result in another column using Javascript.
The string is the form of: for example: Fri 21 Feb 2014, 09:40 AM.
Hence this when converted to a datetime format and exported to excel, the column should be treat as a date.
Can any one of you help me to do it?
Cheers,
Other answers do not take into consideration this question is in a BIRT context.
Create a computed column in your dataset, with "Date time" as datatype
Enter as expression:
new Date(row["myDateStringField"]);
Where "myDateStringField" is your DateTime column in a String format. Then use this computed column in your report instead of the String column.
That's it!
Checkout momentjs!
You can parse your time of any format like
moment("12-25-1995", "MM-DD-YYYY");
In your case, you don't even have to specify the format. It automatically recognizes it.
And you can output ISO format or convert it to a Javascript Date object.
This is extremely easy to do with javascript. The following code will make a date in a format that Excel will recognize as a date.
http://jsfiddle.net/bbankes/d7SwQ/
var dateString = 'Fri 21 Feb 2014, 09:40 AM';
var date = new Date(dateString);
var yr = date.getFullYear();
var mo = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var hr = hours < 10 ? '0' + hours : hours;
var minutes = date.getMinutes();
var min = (minutes < 10) ? '0' + minutes : minutes;
var seconds = date.getSeconds();
var sec = (seconds < 10) ? '0' + seconds : seconds;
var newDateString = yr + '-' + mo + '-' + day;
var newTimeString = hr + ':' + min + ':' + sec;
var excelDateString = newDateString + ' ' + newTimeString;
If you just want to reformat 'Fri 21 Feb 2014, 09:04 AM' as '2014-02-21 09:04', then the following will do:
function stringToTimestamp(s) {
var t = s.match(/[\d\w]+/g);
var months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
function pad(n){return (n<10?'0':'') + +n;}
var hrs = t[4] % 12;
hrs += /pm$/i.test(t[6])? 12 : 0;
return t[3] + '-' + months[t[2].toLowerCase()] + '-' + pad(t[1]) + ' ' +
pad(hrs) + ':' + pad(t[5]);
}
console.log(stringToTimestamp('Fri 21 Feb 2014, 09:04 AM')); // 2014-02-21 09:04
use the ISO format: YYYY-MM-DDTHH:MM:SS or YYYY-MM-DD
new Date('2011-04-11T11:51:00');
or
new Date('2011-04-11');

Timestamp calculated from the current time instead the source date

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.

convert javascript date to c# datetime

I am trying to convert javascript date to c# datetime
JavaScript Code
var date = new Date();
var day = date.getDay();
var month = date.getMonth();
var year = date.getFullYear();
var hour = date.getHours();
var minute = date.getMinutes();
var second = date.getSeconds();
// After this construct a string with the above results as below
var JSDateString = year+ "-" + month + "-" + day + " " + hour + ':' + minute + ':' + second;
C# Code
var JSDateString = "2016-04-02 17:15:45"; // I receive date string via Ajax call in this format
var dt = DateTime.ParseExact(JSDateString , "yyyy-mm-dd HH:mm:ss", CultureInfo.InvariantCulture);
I get invalid datetime format exception. I researched other options in internet but I didn't find any specific answer on how to convert JavaScript datetime to C# datetime.
mm is for minutes, you want MM for month:
var dt = DateTime.ParseExact(JSDateString , "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
This might help with the JavaScript side:
function getDate() {
var date = new Date(),
year = date.getFullYear(),
month = (date.getMonth() + 1).toString(),
formatedMonth = (month.length === 1) ? ("0" + month) : month,
day = date.getDate().toString(),
formatedDay = (day.length === 1) ? ("0" + day) : day,
hour = date.getHours().toString(),
formatedHour = (hour.length === 1) ? ("0" + hour) : hour,
minute = date.getMinutes().toString(),
formatedMinute = (minute.length === 1) ? ("0" + minute) : minute,
second = date.getSeconds().toString(),
formatedSecond = (second.length === 1) ? ("0" + second) : second;
return year + "-" + formatedMonth + "-" + formatedDay + " " + formatedHour + ':' + formatedMinute + ':' + formatedSecond;
};
View a fiddle here: https://jsfiddle.net/kpduncan/de8j318k/
I had too do something like this when I building an application due to not being allowed to add thrid party JS and needing support back to IE8.
As you can see on the MSDN, mm is for minutes (00 - 59) whereas MM is for the month (01 - 12).
var JSDateString = "2016-04-02 17:15:45";
var formatCode = "yyyy-MM-dd HH:mm:ss";
var dt = DateTime.ParseExact(JSDateString , formatCode, CultureInfo.InvariantCulture);
You can see that mm is for minutes because you already use it in your HH:mm:ss.

json object contains php DateTime, how to convert to pretty date string

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;
}

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