I am trying to get date from JavaScript using getUTCDate().
This is giving me wrong output
var date = new Date();
var startDate = new Date(date.getFullYear(), date.getMonth() - 1, 1);
var endDate = new Date(date.getFullYear(), date.getMonth(), 0);
console.log("startDate " + startDate);
startDate = startDate.getUTCFullYear() + "-" + (startDate.getMonth() + 1) + "-" + startDate.getUTCDate();
console.log("first Date " + startDate);
This gives me 2021-4-31 but it should be 2021-4-1
Any idea.
Your startDate and endDate variables are being set to the start and end of the previous month, but in your local time.
When you console.log("startDate " + startDate) in node.js, it will output the date in UTC, which will differ from your start and end date by your current UTC offset (5 hours, 30 minutes).
If we format the date using your local timezone, you will see that it is the expected value.
var date = new Date();
var startDate = new Date(date.getFullYear(), date.getMonth() - 1, 1);
var endDate = new Date(date.getFullYear(), date.getMonth(), 0);
// Formats date variable as a local ISO (ish) string.
function formatLocal(dt) {
let result = dt.getFullYear()
result += "-" + (String(dt.getMonth() + 1).padStart(2, "0") )
result += "-" + (String(dt.getDate()).padStart(2, "0") );
result += "T" + (String(dt.getHours()).padStart(2, "0") );
result += ":" + (String(dt.getMinutes()).padStart(2, "0") );
result += ":" + (String(dt.getSeconds()).padStart(2, "0") );
return result;
}
console.log("startDate (Local):", formatLocal(startDate))
console.log("endDate (Local):", formatLocal(endDate))
console.log("startDate (UTC):", startDate.toISOString())
console.log("endDate (UTC):", endDate.toISOString())
It's because of the time zone which seems to be GMT+02:00 on your computer I guess.
The getUTCDate() method returns the day of the month(from 1 to 31) in
the specified date according to universal time.
link
const date1 = new Date('April 1, 2021 00:00:00 GMT+02:00');
const date2 = new Date('April 1, 2021 00:00:00 GMT+00:00');
console.log(date1.getUTCDate());
// expected output: 31
console.log(date2.getUTCDate());
// expected output: 1
The best solution is to use moment or Luxon library. There is a bunch of formation options. I think your problem is with time zone.
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;
}
This question already has answers here:
How to add 30 minutes to a JavaScript Date object?
(29 answers)
Closed 2 years ago.
I am facing an issue in javascript dates. I want to display previous and after 30min
How should I added previous or after 30min in current dates.
this.setState({
current: new Date().toLocaleTimeString(), //10:30:02 PM
slotTime: new Date().toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
}), //10:30 AM
Output:
10:30 AM //current date
expected:
10:00 AM //previous
10:30 AM //current
11:00 AM //after 30min
anyone help me?
You can simply do it like this:
var currDate = new Date();
var dd = new Date().setMinutes(currDate.getMinutes() - 30); //reduce 30 minutes
var ddPLus = new Date().setMinutes(currDate.getMinutes() + 30); //add 30 minutes
var reductedTime = new Date(dd);
var addedTime = new Date(ddPLus);
console.log("Current time: ", new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })) //current time
console.log("Reduced time: ", reductedTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })) // reduced time by 30mins
console.log("Added time: ", addedTime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })) // added time by 30mins
Hope this help
/* required:
* - timestamp => number of timestamp format
* - format => return format, ex. format 1 (23:59:59), format 2 (23:59)
* return: time with string
*/
function timestampToTime(timestamp, format = 1) {
if (!isNaN(timestamp) || timestamp != undefined) {
let dd = new Date(timestamp)
if (format == 1) {
return ('00' + dd.getHours()).slice(-2) + ':' + ('00' + dd.getMinutes()).slice(-2) + ':' + ('00' + dd.getSeconds()).slice(-2)
} else if (format == 2) {
return ('00' + dd.getHours()).slice(-2) + ':' + ('00' + dd.getMinutes()).slice(-2)
}
} else {
return null
}
}
let dd = + new Date()
let previous = timestampToTime(dd - (1.8e+6)) // 1.8e+6 = 30 min
let current = timestampToTime(dd)
let after = timestampToTime(dd + (1.8e+6)) // 1.8e+6 = 30 min
console.log(previous)
console.log(current)
console.log(after)
Essentially I am trying to convert a date such as 2019-02-09 to 09-02-2019. I have the following:
var newDate = new Date('2019-02-09');
strDate = newDate.getDate() + "-" + (newDate.getMonth() + 1) + "-" + newDate.getFullYear();
which works but will output 9-2-2019. Is there a neat method (ie not checking getDate and getMonth less than 10) to get the output 09-02-2019?
Using toLocaleDateString():
var dt = new Date('2019-02-09');
var x = dt.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' })
.replace(/[^0-9]/g, '-');
console.log(x);
Just use the toLocaleDateString() method and choose en-GB as the locale to return your date in the DD/MM/YYYY format and use a simple split() and join() or regex to replace / with - like this:
Split and Join approach:
var newDate = new Date('2019-02-09');
strDate = newDate.toLocaleDateString('en-GB').split("/").join("-");
alert(strDate);
Regex:
var newDate = new Date('2019-02-09');
strDate = newDate.toLocaleDateString('en-GB').replace(/[^0-9]/g, '-');
alert(strDate);
You could use padStart to achieve your goal.
var newDate = new Date('2019-02-09');
strDate = newDate.getDate().toString().padStart(2, "0") + "-" + (newDate.getMonth() + 1).toString().padStart(2, "0") + "-" + newDate.getFullYear();
console.log(strDate);
Does anyone know how to convert JS dateTime to MySQL datetime? Also is there a way to add a specific number of minutes to JS datetime and then pass it to MySQL datetime?
var date;
date = new Date();
date = date.getUTCFullYear() + '-' +
('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
('00' + date.getUTCDate()).slice(-2) + ' ' +
('00' + date.getUTCHours()).slice(-2) + ':' +
('00' + date.getUTCMinutes()).slice(-2) + ':' +
('00' + date.getUTCSeconds()).slice(-2);
console.log(date);
or even shorter:
new Date().toISOString().slice(0, 19).replace('T', ' ');
Output:
2012-06-22 05:40:06
For more advanced use cases, including controlling the timezone, consider using http://momentjs.com/:
require('moment')().format('YYYY-MM-DD HH:mm:ss');
For a lightweight alternative to momentjs, consider https://github.com/taylorhakes/fecha
require('fecha').format('YYYY-MM-DD HH:mm:ss')
I think the solution can be less clunky by using method toISOString(), it has a wide browser compatibility.
So your expression will be a one-liner:
new Date().toISOString().slice(0, 19).replace('T', ' ');
The generated output:
"2017-06-29 17:54:04"
While JS does possess enough basic tools to do this, it's pretty clunky.
/**
* You first need to create a formatting function to pad numbers to two digits…
**/
function twoDigits(d) {
if(0 <= d && d < 10) return "0" + d.toString();
if(-10 < d && d < 0) return "-0" + (-1*d).toString();
return d.toString();
}
/**
* …and then create the method to output the date string as desired.
* Some people hate using prototypes this way, but if you are going
* to apply this to more than one Date object, having it as a prototype
* makes sense.
**/
Date.prototype.toMysqlFormat = function() {
return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
};
JS time value for MySQL
var datetime = new Date().toLocaleString();
OR
const DATE_FORMATER = require( 'dateformat' );
var datetime = DATE_FORMATER( new Date(), "yyyy-mm-dd HH:MM:ss" );
OR
const MOMENT= require( 'moment' );
let datetime = MOMENT().format( 'YYYY-MM-DD HH:mm:ss.000' );
you can send this in params its will work.
For arbitrary date string,
// Your default date object
var starttime = new Date();
// Get the iso time (GMT 0 == UTC 0)
var isotime = new Date((new Date(starttime)).toISOString() );
// getTime() is the unix time value, in milliseconds.
// getTimezoneOffset() is UTC time and local time in minutes.
// 60000 = 60*1000 converts getTimezoneOffset() from minutes to milliseconds.
var fixedtime = new Date(isotime.getTime()-(starttime.getTimezoneOffset()*60000));
// toISOString() is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ.
// .slice(0, 19) removes the last 5 chars, ".sssZ",which is (UTC offset).
// .replace('T', ' ') removes the pad between the date and time.
var formatedMysqlString = fixedtime.toISOString().slice(0, 19).replace('T', ' ');
console.log( formatedMysqlString );
Or a single line solution,
var formatedMysqlString = (new Date ((new Date((new Date(new Date())).toISOString() )).getTime() - ((new Date()).getTimezoneOffset()*60000))).toISOString().slice(0, 19).replace('T', ' ');
console.log( formatedMysqlString );
This solution also works for Node.js when using Timestamp in mysql.
#Gajus Kuizinas's first answer seems to modify mozilla's toISOString prototype
new Date().toISOString().slice(0, 10)+" "+new Date().toLocaleTimeString('en-GB');
The easiest correct way to convert JS Date to SQL datetime format that occur to me is this one. It correctly handles timezone offset.
const toSqlDatetime = (inputDate) => {
const date = new Date(inputDate)
const dateWithOffest = new Date(date.getTime() - (date.getTimezoneOffset() * 60000))
return dateWithOffest
.toISOString()
.slice(0, 19)
.replace('T', ' ')
}
toSqlDatetime(new Date()) // 2019-08-07 11:58:57
toSqlDatetime(new Date('2016-6-23 1:54:16')) // 2016-06-23 01:54:16
Beware that #Paulo Roberto answer will produce incorrect results at the turn on new day (i can't leave comments). For example:
var d = new Date('2016-6-23 1:54:16'),
finalDate = d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
console.log(finalDate); // 2016-06-22 01:54:16
We've got 22 June instead of 23!
The venerable DateJS library has a formatting routine (it overrides ".toString()"). You could also do one yourself pretty easily because the "Date" methods give you all the numbers you need.
The short version:
// JavaScript timestamps need to be converted to UTC time to match MySQL
// MySQL formatted UTC timestamp +30 minutes
let d = new Date()
let mySqlTimestamp = new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
(d.getMinutes() + 30), // add 30 minutes
d.getSeconds(),
d.getMilliseconds()
).toISOString().slice(0, 19).replace('T', ' ')
console.log("MySQL formatted UTC timestamp: " + mySqlTimestamp)
UTC time is generally the best option for storing timestamps in MySQL. If you don't have root access, then run set time_zone = '+00:00' at the start of your connection.
Display a timestamp in a specific time zone in MySQL with the method convert_tz.
select convert_tz(now(), 'SYSTEM', 'America/Los_Angeles');
JavaScript timestamps are based on your device's clock and include the time zone. Before sending any timestamps generated from JavaScript, you should convert them to UTC time. JavaScript has a method called toISOString() which formats a JavaScript timestamp to look similar to MySQL timestamp and converts the timestamp to UTC time. The final cleanup takes place with slice and replace.
let timestmap = new Date()
timestmap.toISOString().slice(0, 19).replace('T', ' ')
Long version to show what is happening:
// JavaScript timestamps need to be converted to UTC time to match MySQL
// local timezone provided by user's device
let d = new Date()
console.log("JavaScript timestamp: " + d.toLocaleString())
// add 30 minutes
let add30Minutes = new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
(d.getMinutes() + 30), // add 30 minutes
d.getSeconds(),
d.getMilliseconds()
)
console.log("Add 30 mins: " + add30Minutes.toLocaleString())
// ISO formatted UTC timestamp
// timezone is always zero UTC offset, as denoted by the suffix "Z"
let isoString = add30Minutes.toISOString()
console.log("ISO formatted UTC timestamp: " + isoString)
// MySQL formatted UTC timestamp: YYYY-MM-DD HH:MM:SS
let mySqlTimestamp = isoString.slice(0, 19).replace('T', ' ')
console.log("MySQL formatted UTC timestamp: " + mySqlTimestamp)
This is by far the easiest way I can think of
new Date().toISOString().slice(0, 19).replace("T", " ")
Full workaround (to mantain the timezone) using #Gajus answer concept:
var d = new Date(),
finalDate = d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
console.log(finalDate); //2018-09-28 16:19:34 --example output
I have given simple JavaScript date format examples please check the bellow code
var data = new Date($.now()); // without jquery remove this $.now()
console.log(data)// Thu Jun 23 2016 15:48:24 GMT+0530 (IST)
var d = new Date,
dformat = [d.getFullYear() ,d.getMonth()+1,
d.getDate()
].join('-')+' '+
[d.getHours(),
d.getMinutes(),
d.getSeconds()].join(':');
console.log(dformat) //2016-6-23 15:54:16
Using momentjs
var date = moment().format('YYYY-MM-DD H:mm:ss');
console.log(date) // 2016-06-23 15:59:08
Example please check https://jsfiddle.net/sjy3vjwm/2/
var _t = new Date();
if you want UTC format simply
_t.toLocaleString('indian', { timeZone: 'UTC' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
or
_t.toISOString().slice(0, 19).replace('T', ' ');
and if want in specific timezone then
_t.toLocaleString('indian', { timeZone: 'asia/kolkata' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
Using toJSON() date function as below:
var sqlDatetime = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60 * 1000).toJSON().slice(0, 19).replace('T', ' ');
console.log(sqlDatetime);
Datetime in a different time zone
This uses #Gayus solution using the format outputted from toISOString() but it adjusts the minutes to account for the time zone.
Final format: 2022-03-01 13:32:51
let ts = new Date();
ts.setMinutes(ts.getMinutes() - ts.getTimezoneOffset());
console.log(ts.toISOString().slice(0, 19).replace('T', ' '));
I am surprised that no one mention the Swedish date time format for javascript yet.
the BCP 47 language tag for the Swedish language is sv-SE that you can use for the new Date "locale" parameter.
I am not saying it is a good practice, but it works.
console.log(new Date().toLocaleString([['sv-SE']])) //2022-09-10 17:02:39
A simple solution is send a timestamp to MySQL and let it do the conversion. Javascript uses timestamps in milliseconds whereas MySQL expects them to be in seconds - so a division by 1000 is needed:
// Current date / time as a timestamp:
let jsTimestamp = Date.now();
// **OR** a specific date / time as a timestamp:
jsTimestamp = new Date("2020-11-17 16:34:59").getTime();
// Adding 30 minutes (to answer the second part of the question):
jsTimestamp += 30 * 1000;
// Example query converting Javascript timestamp into a MySQL date
let sql = 'SELECT FROM_UNIXTIME(' + jsTimestamp + ' / 1000) AS mysql_date_time';
I needed a function to return the sql timestamp format in javascript form a selective timezone
<script>
console.log(getTimestamp("Europe/Amsterdam")); // Europe/Amsterdam
console.log(getTimestamp()); // UTC
function getTimestamp(timezone) {
if (timezone) {
var dateObject = new Date().toLocaleString("nl-NL", { // it will parse with the timeZone element, not this one
timeZone: timezone, // timezone eg "Europe/Amsterdam" or "UTC"
month: "2-digit",
day: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
let [dateRaw, timeRaw] = dateObject.split(" ");
let [day, month, year] = dateRaw.split("-");
var timestamp = year + "-" + month + "-" + day + " " + timeRaw;
}else{
// UTC from #Gajus, 95% faster then the above
timestamp = new Date().toISOString().slice(0, 19).replace("T", " ");
}
return timestamp; // YYYY-MM-DD HH:MI:SS
}
</script>
If you are using Date-fns then the functionality can be achived easily using format function.
const format = require("date-fns/format");
const date = new Date();
const formattedDate = format(date, "yyyy-MM-dd HH:mm:ss")
This is the easiest way -
new Date().toISOString().slice(0, 19).replace("T", " ")
I'm using this long time and it's very helpful for me, use as you like
Date.prototype.date=function() {
return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')
}
Date.prototype.time=function() {
return String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
}
Date.prototype.dateTime=function() {
return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')+' '+String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
}
Date.prototype.addTime=function(time) {
var time=time.split(":")
var rd=new Date(this.setHours(this.getHours()+parseInt(time[0])))
rd=new Date(rd.setMinutes(rd.getMinutes()+parseInt(time[1])))
return new Date(rd.setSeconds(rd.getSeconds()+parseInt(time[2])))
}
Date.prototype.addDate=function(time) {
var time=time.split("-")
var rd=new Date(this.setFullYear(this.getFullYear()+parseInt(time[0])))
rd=new Date(rd.setMonth(rd.getMonth()+parseInt(time[1])))
return new Date(rd.setDate(rd.getDate()+parseInt(time[2])))
}
Date.prototype.subDate=function(time) {
var time=time.split("-")
var rd=new Date(this.setFullYear(this.getFullYear()-parseInt(time[0])))
rd=new Date(rd.setMonth(rd.getMonth()-parseInt(time[1])))
return new Date(rd.setDate(rd.getDate()-parseInt(time[2])))
}
and then just:
new Date().date()
which returns current date in 'MySQL format'
for add time is
new Date().addTime('0:30:0')
which will add 30 minutes.... and so on
Solution built on the basis of other answers, while maintaining the timezone and leading zeros:
var d = new Date;
var date = [
d.getFullYear(),
('00' + d.getMonth() + 1).slice(-2),
('00' + d.getDate() + 1).slice(-2)
].join('-');
var time = [
('00' + d.getHours()).slice(-2),
('00' + d.getMinutes()).slice(-2),
('00' + d.getSeconds()).slice(-2)
].join(':');
var dateTime = date + ' ' + time;
console.log(dateTime) // 2021-01-41 13:06:01
Simple: just Replace the T.
Format that I have from my <input class="form-control" type="datetime-local" is :
"2021-02-10T18:18"
So just replace the T, and it would look like this: "2021-02-10 18:18" SQL will eat that.
Here is my function:
var CreatedTime = document.getElementById("example-datetime-local-input").value;
var newTime = CreatedTime.replace("T", " ");
Reference:
https://www.tutorialrepublic.com/faq/how-to-replace-character-inside-a-string-in-javascript.php#:~:text=Answer%3A%20Use%20the%20JavaScript%20replace,the%20global%20(%20g%20)%20modifier.
https://www.tutorialrepublic.com/codelab.php?topic=faq&file=javascript-replace-character-in-a-string