I'm having trouble converting an example string: 'Sun Feb 02 19:12:44 +0000 2014'
to mysql dateTime format in javascript
any help would be greatly appreciated
You can convert date time to mysql format using this code:
var myDate = new Date('Sun Feb 02 19:12:44 +0000 2014'),
year = myDate.getFullYear(),
month = ('0' + (myDate.getMonth() + 1)).slice(-2),
day = ('0' + myDate.getDate()).slice(-2),
hour = ('0' + myDate.getHours()).slice(-2),
minute = ('0' + myDate.getMinutes()).slice(-2),
seconds = ('0' + myDate.getSeconds()).slice(-2),
mysqlDateTime = [year, month, day].join('-') + ' ' + [hour, minute, seconds].join(':');
However I would suggest to send it to backend as timestamp (+(new Date('Sun Feb 02 19:12:44 +0000 2014'))) or formatted string (myDate.toISOString()) and proceed with conversion there.
try this:
var d = new Date('Sun Feb 02 19:12:44 +0000 2014');
var month = d.getMonth();
if(month < 10)
month = "0" + month;
var day = d.getDate();
if(day < 10)
day = "0" + day;
hour = d.getHours();
if(hour < 10)
hour = "0" + hour;
minute = d.getMinutes();
if(minute < 10)
minute = "0" + minute;
seconds = d.getSeconds();
if(seconds < 10)
seconds = "0" + seconds;
var mysqlDate = d.getFullYear() + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + seconds;
Related
I am facing an issue in javascript dates . i want to do same date format both previous date and start date
Excepted Output previous date
after 12AM shows 00:00:00 to 12:00:00
after 12PM shows 00:00:00 to 12:00:00
format
previous date 2020-05-10 16:31:28
start date
2020-05-10 02:00:00 //sample data
2020-05-10 05:00:00
My code:
var currentdate = new Date();
var prevdate = new Date(); //previous date
prevdate.setTime(currentdate.getTime() - (30 * 60 * 1000));
var newprevious = GetFormattedDate(prevdate);
console.log(newprevious);
//Date format yyyy-mm-dd h:MM:ss
function GetFormattedDate(date) {
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + (date.getDate())).slice(-2);
var year = date.getFullYear();
var hour = ("0" + (date.getHours())).slice(-2);
var min = ("0" + (date.getMinutes())).slice(-2);
var seg = ("0" + (date.getSeconds())).slice(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + seg;
}
Note: i can't change the start_date it is fixed format
what should i change ? Anyone help me?
This really is a date formatting issue so probably a duplicate of How to format a JavaScript date.
As Drago96 has answered, you can use the remainder operator % to modify the hours value and add am or pm as appropriate
An alternative to using get methods and processing each part is to use the formatting options of Intl.DateTimeFormat object and formatToParts, e.g.
function formatDate(date) {
let parts = new Intl.DateTimeFormat('default',{
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: true
}).formatToParts(date).reduce((acc, part) => {
if (part.type != 'literal') {
acc[part.type] = part.value;
}
return acc;
}, Object.create(null));
return `${parts.year}-${parts.month}-${parts.day}\
${parts.hour}:${parts.minute}:${parts.minute}\
${parts.dayPeriod}`;
}
console.log(formatDate(new Date()));
If the problem is just that the hour is not in am/pm format, you can modify your function this way, using the modulo operator (I've also added am/pm at the end of the string):
var currentdate = new Date();
var prevdate = new Date(); //previous date
prevdate.setTime(currentdate.getTime() - (30 * 60 * 1000));
var newprevious = GetFormattedDate(prevdate);
console.log(newprevious);
//Date format yyyy-mm-dd h:MM:ss
function GetFormattedDate(date) {
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + (date.getDate())).slice(-2);
var year = date.getFullYear();
// EDIT:
var hour = date.getHours()%12; // using the modulo operator, you convert the hours to a range between 0 and 12
if (hour == 0) {
hour = 12;
}
var timeOfDay = "am";
if (date.getHours() >= 12) {
timeOfDay = "pm";
}
hour = ("0" + hour).slice(-2);
// END EDIT
var min = ("0" + (date.getMinutes())).slice(-2);
var seg = ("0" + (date.getSeconds())).slice(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + seg + " " + timeOfDay;
}
How to change this 27 June 2018 - 05:25 into Y-m-d H:i:s format?
I don't know how and I'm just a beginner in javascript, can someone help me?
Using moment.js you can parse and format:
var dateStr = moment('27 June 2018 - 05:25', 'DD MMM YYYY - HH:mm').format('YYYY-MM-DD HH:mm:ss');
console.log(dateStr);
Here's a Fiddle: https://jsfiddle.net/z7jz5y8t/1/
You can set custom format like this
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return date.getFullYear() + "-"+ (date.getMonth()+1) + "-" + date.getDate() + " " + strTime;
}
var d = new Date();
var e = formatDate(d);
alert(e);
Also possible duplicate of this 'Javascript format date / time'
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 date in the following format:
Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)
Can anyone tell me how to parse the date
Wed Jul 17 2013
and time out of this without using string functions
1:00pm
One of the simplest ways is to make sure your LOCALES are set properly, which allows you to do something like this:
var myStrDate = 'Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)';
var myDate = Date.parse(myStrDate);
var myDateOnly = myDate.toLocaleDateString();
var myTimeOnly = myDate.toLocaleTimeString();
Here's a great place to start: http://www.w3schools.com/jsref/jsref_obj_date.asp
You can construct a Date object with the date string, combined with additional functions to get the required output. dayname() returns the dayname, monthname() returns the three-letter month name.
I've used console.info() for outputting results - alert() can be used as an alternative if appropriate.
function dayname(d)
{
var names = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri","Sat" ];
return names[d.getDay()];
}
function monthname(d)
{
var names = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
return names[d.getMonth()];
}
// construct new date object passing date string as parameter
var d = new Date("Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)");
console.info(dayname(d) + ' ' + monthname(d) + ' ' + d.getDate() + ' ' + d.getFullYear());
For the time, this gettime() function checks the hour to output am or pm correctly, and for correct formatting-:
function gettime(d)
{
var ampm = "am";
var hour = d.getHours();
var mins = d.getMinutes();
if (hour >= 12)
{
hour = hour - 12;
ampm = "pm";
}
if (hours < 10)
hours = "0" + hours;
if (mins < 10)
mins = "0" + mins;
return hour + ":" + mins + ampm;
}
console.info(gettime(d));
var ms = Date.parse(new Date("Wed Jul 17 2013 13:00:00 GMT-0700 (PDT)"));
var curr_date = ms.getDate();
var curr_month = ms.getMonth() + 1; //Months are zero based
var curr_year = ms.getFullYear();
var hours = ms.getHours();
var mins = ms.getMinutes();
suf = (hours >= 12)? 'pm' : 'am';
hours = hours % 12;
document.write(curr_date + "-" + curr_month + "-" + curr_year + " " + hours + ":" + min + " " + suffix);
Also try using moment.js, you can format dateTime as you wish.
Here great reference to learn date functions in javascript https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
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