I have a timestamp format which is just like below which is an int.
1631514003973
I am passing this value to an API which is built with Node.JS. How can I convert this into Mysql DateTime format?
I checked this answer but it is about getting the current date and not converting a timestamp. I am coming from a Java background so this is bit confusing for me.
You can pass the Date object of JavaScript directly to MySQL. And MySQL will automatically generate the DateTime format from that Date object.
const date = new Date(1631514003973);
I assume that integer represents number in milliseconds since the Epoch time. If that is the case try this code:
const numberOfMs = 1631514003973;
const epochDate = new Date(1970,1,1);
const myDate = new Date(epochDate .getTime() + numberOfMs);
For that you can use either in nodejs layer. You need to convert the timestamp to date using below and use in the mysql query.
const date = new Date(1631514003973);
console.log(date)
For the use direct in mysql you can use mysql date function and
SELECT DATE_FORMAT(FROM_UNIXTIME(DATE(1631514003973)), '%e %b %Y') AS 'date_formatted' FROM table
we need to create a new function using JavaScript.
<script>
var timestamp = 1607110465663
var date = new Date(timestamp);
console.log("Date: "+date.getDate()+
"/"+(date.getMonth()+1)+
"/"+date.getFullYear()+
" "+date.getHours()+
":"+date.getMinutes()+
":"+date.getSeconds());
</script>
Output:
Date: 4/12/2020 19:34:25
If you want only date (MM/DD/YYYY), you should fallow this:
var timestamp=1370001284;
var todate=new Date(timestamp).getDate();
var tomonth=new Date(timestamp).getMonth()+1;
var toyear=new Date(timestamp).getFullYear();
var original_date=tomonth+'/'+todate+'/'+toyear;
console.log(original_date);
Related
I'm trying to add the current time to an existing date but I'm not sure how to do it.
I'm importing stuff into a Postgres database and need a ISO string to update the "updatedAt" column, the imported stuff only has a date like this tho: "2022-03-15", no time.
How would I add the time to this and turn it into a proper ISO string for my database?
const date = new Date('2022-03-15')
const iso = date.toISOSTring() // how to add the current time?
-
Should look like this: "2022-03-15 09:36:54.292613"
Thank you! :)
Try to use dayJs and add the time that you need, https://day.js.org/docs/en/parse/string
dayjs('2018-04-04T16:00:00.000Z')
dayjs('2018-04-13 19:18:17.040+02:00')
dayjs('2018-04-13 19:18')
You can set the time units into date from the current date-time i.e. new Date().
const date = new Date("2022-03-15");
const now = new Date();
date.setHours(now.getHours());
date.setMinutes(now.getMinutes());
date.setSeconds(now.getSeconds());
date.setMilliseconds(now.getMilliseconds());
console.log(date.toISOString());
console.log(date.toISOString().replace("T", " ").replace("Z", " "));
I am using a library to calculate the age from date of birth. I am taking date of birth as an input which is in the format of dd/mm/yy but the library that calculated the age accepts it in the format of mm/dd/yy. One solution to this is to change the date selector format in the application but I dont want to do that since it gets confusing.
I searched the solution on stackoverflow but couldnt find the solution here- How to format a JavaScript date
How about a simple split and join:
var yourDate = "10/12/2021";
var arrayOfDate = yourDate.split("/");
console.log([arrayOfDate[1], arrayOfDate[0], arrayOfDate[2]].join('/'));
Just split it with / and then use destructure it and get the desired result as:
const result = `${mm}/${dd}/${yy}`;
var oldDate = "10/12/21";
var [dd, mm, yy] = oldDate.split("/");
const newDate = `${mm}/${dd}/${yy}`;
console.log(newDate);
I've done endless searching but cannot find a solution that works for me. I am storing records in a mysql database that logs the UTC time it was created (UTC_TIMESTAMP()). I need to present the data to the user (using JavaScript) in their local time. I've tried the following and it is not working:
JavaScript:
function localizeDateStr(dateToConvert,divId){
newDate = new Date(dateToConvert);
document.getElementById(divId).innerHTML = newDate.toString();
}
HTML:
<div id="<?php echo $divId ?>" class="td-short"></div>
<script type="text/javascript">window.onload = localizeDateStr('<?php echo $entryTime;?>','<?php echo $divId;?>');</script>
The UTC date that is stored in the db is the same date that is being displayed.I am not seeing a converted date. Any help would be appreciated. Please advise.
Parsing a string through the Date constructor (or through Date.parse) is very sensitive to the format of the input string. With the value you gave in comments '2019-03-20 17:43:53', most implementations will interpret this in terms of local time. However, the specification does not require conformance of that, as it only describes a very particular format. Anything else is implementation dependent.
Assuming your strings are consistently in this format, and you want it interpreted as UTC, your options are:
Adjust the string to include a T separator between date and time parts, and end with Z to indicate UTC.
var newDate = new Date(dateToConvert.replace(' ','T') + 'Z');
Parse the string yourself:
var parts = dateToConvert.split(/[-: ]/g).map((x) => parseInt(x));
parts[1]--; // Months are 0-11, so adjust
var newDate = new Date(Date.UTC(...parts));
Use a library like Luxon:
var dt = luxon.DateTime.fromFormat(dateToConvert,
'yyyy-MM-dd HH:mm:ss', { zone: 'UTC' });
var newDate = dt.toJSDate();
or Moment:
var newDate = moment.utc(dateToConvert).toDate();
//In Node/JS
myDate = moment(data.myTime.format('YYYY/MM/DD HH:MM:SS')).toISOString();
//myDate shows '2014-09-24T04:09:00.000Z'
Insert INTO (dateColumn..) Values(myDate)...
This is the error I get after inserting, note column in Mysql is a "datetime" type.
MySQL Error:: { [Error: ER_TRUNCATED_WRONG_VALUE: Incorrect datetime value: '2014-09- 24T04:09:00.000Z' for column '_dateColumn' at row 1]
code: 'ER_TRUNCATED_WRONG_VALUE',
This result happens because you are using the toISOString() method and it is not a valid format to insert into your DATETIME column. The correct format probably is YYYY-MM-DD HH:MM:SS(I think it depends on MySQL configuration, but this is the default) as the docs points out.
So you should try using moment's format() method like this:
myDate = moment(data.myTime.format('YYYY/MM/DD HH:mm:ss')).format("YYYY-MM-DD HH:mm:ss");
In fact, I don't know what data.myTime is, but if its a moment object too, you can change the first format() method and remove the second one.
DontVoteMeDown answer is right, except that the minutes 'mm' and seconds 'ss' need to be in lowercase, otherwise a wrong value is returned:
myDate = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
Also, you should check the value sent by javascript before to do your SQL query, in PHP:
DateTime::createFromFormat('Y-m-d H:i:s', $myDate);
Will return false if the date is misformatted.
Here's a function extension to format it into the MySQL DateTime format
moment.prototype.toMySqlDateTime = function () {
return this.format('YYYY-MM-DD HH:mm:ss');
};
You'll be able to do: moment().toMySqlDateTime();
(I'm working with Node.js, Express and MySql and this has worked for me:)
var momentDate=new moment('2018-08-31T20:13:00.000Z');
var readyToInsert=momentDate.format("YYYY-MM-DD HH:mm:ss");
To generate mysql format datetime you can use this:
var moment = require('moment');
let currentTimestamp = moment().unix();//in seconds
let currentDatetime = moment(currentTimestamp*1000).format("YYYY-MM-DD HH:mm:ss");//mysql datetime.
currentTimestamp = moment(currentDatetime).valueOf();//current timestamp in milliseconds
moment().format("YYYY-MM-DD HH:mm:ss")
I think this is the correct format. Otherwise you get the months inserted in your minutes, and you also get seconds above 60.
myDate = moment(data.myTime.format('YYYY/MM/DD HH:MM:ss')).format("YYYY-MM-DD HH:MM:SS");
Tested in Chrome with Moment.js 2.9.0
My value contains "08.07.1987", how to retrieve the date object for this string. new Date(val) gives correct date object values only for the string value that contains "/" format. can any one let me know hot to create date object for the values which contains "." or "-". in its format.
How about just adjusting the string to suit your needs?
var date1 = new Date("08.07.1987".replace('.','/'));
var date2 = new Date("08-07-1987".replace('-','/'));
You will need to be careful when asking Javascript to interpret a date in this format. As you can probably imagine, a date listed as "08.07.1987" doesn't really specify whether it's August 7th or July 8th.
In general, your best bet will be to specify a date format and parse accordingly.
you have to split the string into tokens for month date and year and then create it using JS Date API.
var date="08.07.1987";
var newDate = date.replace(/(\.|-)/g,"/"));
var dateObject = new Date(newDate);
Replace the delimiters?
var dateStr = "08.07.1987",
dateObj = new Date(dateStr.replace(/[-.]/g,"/"));
Of course you can encapsulate that in a function if need be...
try this new Date("08.07.1987".replace('.','/','g')); tested on firefox only