Transform date to DD/MM/YY - javascript

I get the date from server in such format: 2019-01-24 00:00:00
How to convert it to 24-01-2019?
I use:
new Date(dateFromServer).toLocaleDateString()
but it returns 01/24/19.

as seen here Format date to MM/dd/yyyy in JavaScript
var date = new Date(dateFromServer);
alert(date.getDate() + '-' + (date.getMonth() + 1) + '-' + date.getFullYear());

Avoid answers that suggest parsing, it doesn't make sense to parse a string to a Date and reformat it just to get back the values you started with, given the risks of using the built–in parser (e.g. in Safari, new Date('2019-01-24 00:00:00') returns an invalid Date).
To reformat a date, just split it into the parts and put it back as you want:
// #param {string} s - timestamp in format YYYY-MM-DD HH:mm:ss
function reformatDateString(s) {
var b = s.split(/\D/);
return `${b[1]}/${b[2]}/${b[0]}`
}
console.log(reformatDateString('2019-01-24 00:00:00'));

Related

How to add days to javascript unix timestamp? [duplicate]

I want to convert date to timestamp, my input is 26-02-2012. I used
new Date(myDate).getTime();
It says NaN.. Can any one tell how to convert this?
Split the string into its parts and provide them directly to the Date constructor:
Update:
var myDate = "26-02-2012";
myDate = myDate.split("-");
var newDate = new Date( myDate[2], myDate[1] - 1, myDate[0]);
console.log(newDate.getTime());
Try this function, it uses the Date.parse() method and doesn't require any custom logic:
function toTimestamp(strDate){
var datum = Date.parse(strDate);
return datum/1000;
}
alert(toTimestamp('02/13/2009 23:31:30'));
this refactored code will do it
let toTimestamp = strDate => Date.parse(strDate)
this works on all modern browsers except ie8-
There are two problems here.
First, you can only call getTime on an instance of the date. You need to wrap new Date in brackets or assign it to variable.
Second, you need to pass it a string in a proper format.
Working example:
(new Date("2012-02-26")).getTime();
UPDATE: In case you came here looking for current timestamp
Date.now(); //as suggested by Wilt
or
var date = new Date();
var timestamp = date.getTime();
or simply
new Date().getTime();
/* console.log(new Date().getTime()); */
You need just to reverse your date digit and change - with ,:
new Date(2012,01,26).getTime(); // 02 becomes 01 because getMonth() method returns the month (from 0 to 11)
In your case:
var myDate="26-02-2012";
myDate=myDate.split("-");
new Date(parseInt(myDate[2], 10), parseInt(myDate[1], 10) - 1 , parseInt(myDate[0]), 10).getTime();
P.S. UK locale does not matter here.
To convert (ISO) date to Unix timestamp, I ended up with a timestamp 3 characters longer than needed so my year was somewhere around 50k...
I had to devide it by 1000:
new Date('2012-02-26').getTime() / 1000
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
+ ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
.getSeconds()) : (now.getSeconds())));
}
For those who wants to have readable timestamp in format of, yyyymmddHHMMSS
> (new Date()).toISOString().replace(/[^\d]/g,'') // "20190220044724404"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -3) // "20190220044724"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -9) // "20190220"
Usage example: a backup file extension. /my/path/my.file.js.20190220
Your string isn't in a format that the Date object is specified to handle. You'll have to parse it yourself, use a date parsing library like MomentJS or the older (and not currently maintained, as far as I can tell) DateJS, or massage it into the correct format (e.g., 2012-02-29) before asking Date to parse it.
Why you're getting NaN: When you ask new Date(...) to handle an invalid string, it returns a Date object which is set to an invalid date (new Date("29-02-2012").toString() returns "Invalid date"). Calling getTime() on a date object in this state returns NaN.
JUST A REMINDER
Date.parse("2022-08-04T04:02:10.909Z")
1659585730909
Date.parse(new Date("2022-08-04T04:02:10.909Z"))
1659585730000
/**
* Date to timestamp
* #param string template
* #param string date
* #return string
* #example datetotime("d-m-Y", "26-02-2012") return 1330207200000
*/
function datetotime(template, date){
date = date.split( template[1] );
template = template.split( template[1] );
date = date[ template.indexOf('m') ]
+ "/" + date[ template.indexOf('d') ]
+ "/" + date[ template.indexOf('Y') ];
return (new Date(date).getTime());
}
The below code will convert the current date into the timestamp.
var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);
The first answer is fine however Using react typescript would complain because of split('')
for me the method tha worked better was.
parseInt((new Date("2021-07-22").getTime() / 1000).toFixed(0))
Happy to help.
In some cases, it appears that some dates are stubborn, that is, even with a date format, like "2022-06-29 15:16:21", you still get null or NaN. I got to resolve mine by including a "T" in the empty space, that is:
const inputDate = "2022-06-29 15:16:21";
const newInputDate = inputDate.replace(" ", "T");
const timeStamp = new Date(newInputDate).getTime();
And this worked fine for me! Cheers!
It should have been in this standard date format YYYY-MM-DD, to use below equation. You may have time along with example: 2020-04-24 16:51:56 or 2020-04-24T16:51:56+05:30. It will work fine but date format should like this YYYY-MM-DD only.
var myDate = "2020-04-24";
var timestamp = +new Date(myDate)
You can use valueOf method
new Date().valueOf()
a picture speaks a thousand words :)
Here I am converting the current date to timestamp and then I take the timestamp and convert it to the current date back, with us showing how to convert date to timestamp and timestamp to date.
The simplest and accurate way would be to add the unary operator before the date
console.log(`Time stamp is: ${Number(+new Date())}`)
Answers have been provided by other developers but in my own way, you can do this on the fly without creating any user defined function as follows:
var timestamp = Date.parse("26-02-2012".split('-').reverse().join('-'));
alert(timestamp); // returns 1330214400000
Simply performing some arithmetic on a Date object will return the timestamp as a number. This is useful for compact notation. I find this is the easiest way to remember, as the method also works for converting numbers cast as string types back to number types.
let d = new Date();
console.log(d, d * 1);
This would do the trick if you need to add time also
new Date('2021-07-22 07:47:05.842442+00').getTime()
This would also work without Time
new Date('2021-07-22 07:47:05.842442+00').getTime()
This would also work but it won't Accept Time
new Date('2021/07/22').getTime()
And Lastly if all did not work use this
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Note for Month it the count starts at 0 so Jan === 0 and Dec === 11
+new Date(myDate)
this should convert myDate to timeStamp

Convert a AM/PM date string to JavaScript date using jQuery

I have a date string like this 20/09/2018 12:00 AM. I need to stop to put the previous date than today. I have searched the web for it, but no answer found with this format.
I need the default date format of JavaScript so that I can compare with new Date() value. When I use the following format it show the message that says invalid date because of my dd/MM/yyyy hh:mm tt format.
alert(new Date("20/09/2018 12:00 AM"));
Igor recommended using moment.js to solve this — it is a widely used date/time library.
With moment.js you can do this:
var m = moment("20/09/2018 3:14 PM", "DD/MM/YYYY h:mm a");
var d = m.toDate();
The first line creates a "moment" object by parsing the date according to the format string specified as the second argument. See http://momentjs.com/docs/#/parsing/
The second line gets the native javascript Date object that the moment object encapsulates; however, moment can do so many things you may not need to get back that native object.
See the moment docs.
Your format isn't valid, thus you're getting invalid date error. So, using your format(dd/MM/yyyy hh:mm tt) we'll grab the year, month, day, hours and the minutes, then we'll reformat it as an acceptable format by the Date constructor and create a Date instance.
Here's a function that do all what being said and returns a Date instance which you can compare it with another Date instance:
function convertToDate(str) {
// replace '/' with '-'
str = str.replace(/\//ig, '-');
/**
* extracting the year, month, day, hours and minutes.
* the month, day and hours can be 1 or 2 digits(the leading zero is optional).
* i.e: '4/3/2022 2:18 AM' is the same as '04/03/2022 02:18 AM' => Notice the absence of the leading zero.
**/
var y = /\-([\d]{4})/.exec(str)[1],
m = /\-([\d]{2}|[\d])/.exec(str)[1],
d = /([\d]{2}|[\d])\-/.exec(str)[1],
H = /\s([\d]{2}|[\d]):/.exec(str)[1],
i = /:([\d]{2})/.exec(str)[1],
AMorPM = /(AM|PM)/.exec(str)[1];
// return a Date instance.
return new Date(y + '-' + m + '-' + d + ' ' + H + ':' + i + ' ' + AMorPM)
}
// testing...
var str1 = '20/09/2018 12:00 AM';
var str2 = '8/2/2018 9:00 PM'; // leading zero is omitted.
console.log(convertToDate(str1));
console.log(convertToDate(str2));
The Date depends on the user's/server's location, two users may have
different results.
Learn more
about Date.
Hope I pushed you further.

Parse date in javascript issues

I get such date in javascript
var val = "1960-05-15T20:00:00"
But if I do
var date = new Date(val);
The data I get is one day later:
1960-05-16 // I use this to obtain it: Ext.Date.format(new Date(val), 'm/d/Y')
Can you help me how to parse this date? and get correct date with 1960-05-15?
Your date format is ISO 8601 represented as the local time with an offset to UTC appended.
The Ext.Date singleton support this format with the c flag.
var parsedDate = Ext.Date.parse('1960-05-15T20:00:00', 'c');
var dateStr = Ext.Date.format(parsedDate, 'Y-m-d');
// "1960-05-15"
Have a look at the Sencha ExtJs 6.2.1 documentation Ext.Date for further informations.
You can use native JS to accomplish the output of the Date object in to this format yyyy-mm-dd
Like so:
var val = '1960-05-15T20:00:00';
var d = new Date(val);
var date = d.getFullYear() + '-' + ('0' + (d.getMonth() + 1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2);
console.log(date);
When you do
var a = new Date(someDate)
variable a contains date according to your local timezone.
If you want date in same format as you entered , use toISOString method
var a = (new Date(someDate)).toISOString()
My recommendation would be, you can only assume the timezone from where the date is coming from. If you know exactly where that date is coming from, a.k.a London, New York, Sidney, etc... then you can use momentjs to set the UTC offset
var val = "1960-05-15T20:00:00"
// these are equivalent
moment(val).utcOffset("+08:00");
moment(val).utcOffset(8);
moment(val).utcOffset(480);
So the OP has said they're in
Tbilisi, Georgia GMT + 4.00
so
moment(val).utcOffset("+04:00");

Convert ISO date to international date type javascript

I want to filter data by current month (maybe additionally add next month data). I don't know how to go from the beginning.
In theory I think I could compare current month and month date from my data and then to display data only if two months variables match.
I thought I should start like this:
var myDate = new Date();
var thisMonth = new Date(myDate);
thisMonth.setMonth(myDate.getMonth()+1);
var nextMonth = new Date(myDate);
nextMonth.setMonth(myDate.getMonth()+2);
Thank you in advance for any kind of help!
Additional detailed explanation:
I copied SharePoint 2013 list whose data I displayed on SharePoint site page.
In content editor web part I wrote javascript code to show that list as a table.
I have two date columns (from/until) but they are displayed in table as YYYY-MM-DD HH:MM:SS. Looks to me like ISO date format. I saw several examples how to convert in js that type of date into date type like DD.MM.YYYY. None worked for me or I didn't know how to do it correctly. So I created calculated field that will present date type as text/string, after this I managed to show date on js table the way I wanted.
You should not parse strings with the Date constructor (or Date.parse, they are equivalent for parsing) as it's largely implementation dependent and notoriously unreliable.
I have two date columns (from/until) but they are displayed in table as YYYY-MM-DD HH:MM:SS. Looks to me like ISO date format.
Almost. The extended format is YYYY-MM-SSTHH:MM:SS, the T can be replaced by a space on agreement between parties exchanging the date but it's not strictly correct. If the timezone is omitted, it's treated as a "local" date (i.e. the host timezone offset is used in calculating the moment in time that it represents).
According to ECMA-262, if the format is not correct, browsers can either:
Treat it as invalid ISO 8601 and return an invalid date
Treat it as not ISO 8601 and fall back to whatever parsing algorithm they wish to use
So given:
new Date('2017-01-01 23:12:12')
Firefox returns a Date for 1 Jan 2017 23:12:12 in the host time zone, Safari returns an invalid date. Both are consistent with the standard.
So if you need a Date object, you should parse the string manually using either a library (e.g. fecha.js or moment.js) or a simple function.
But anyway, you don't need to parse the strings to a Date to reformat the string, just use string methods and avoid Date parsing vagaries completely.
function filterCurrentMonth() {
// Create string for comparison
var d = new Date();
var currentMonth = d.getFullYear() + '-' + ('0' + (d.getMonth()+1)).slice(-2);
// Hide rows that don't have string in the first cell
var rows = document.getElementById('t0').rows;
[].forEach.call(rows, function(row) {
if (row.cells[0].textContent.indexOf(currentMonth) == -1) {
row.style.display = 'none';
} else {
row.style.display = '';
}
});
}
function filterNone() {
var rows = document.getElementById('t0').rows;
[].forEach.call(rows, function(row) {
row.style.display = '';
});
}
#t0 {
font-size: 60%;
}
<button onclick="filterCurrentMonth()">Show only current month rows</button>
<button onclick="filterNone()">Show all rows</button>
<table id="t0">
<tr><td>2017-01-01 23:12:12<tr><td>2017-02-01 23:12:12<tr><td>2017-05-01 23:12:12
<tr><td>2017-03-01 23:12:12<tr><td>2017-04-01 23:12:12<tr><td>2017-12-01 23:12:12
<tr><td>2017-10-01 23:12:12<tr><td>2017-11-01 23:12:12<tr><td>2017-06-01 23:12:12
<tr><td>2017-07-01 23:12:12<tr><td>2017-09-01 23:12:12<tr><td>2017-08-01 23:12:12
<tr><td>2017-01-01 23:12:12<tr><td>2017-02-01 23:12:12<tr><td>2017-05-01 23:12:12
<tr><td>2017-03-01 23:12:12<tr><td>2017-04-01 23:12:12<tr><td>2017-12-01 23:12:12
<tr><td>2017-10-01 23:12:12<tr><td>2017-11-01 23:12:12<tr><td>2017-06-01 23:12:12
<tr><td>2017-07-01 23:12:12<tr><td>
<!-- begin snippet: js hide: false console: true babel: false -->
23:12:122017-08-01 23:12:12
Similarly, if you want to reformat the string to be DD.MM.YYYY you can just reformat the string:
/* Format string in YYYY-MM-DD HH:mm:ss format to DD.MM.YYYY
** #param {string} s - string in YYYY-MM-DD HH:mm:ss format
** #returns {string} in DD.MM.YYYY format
*/
function formatYMDtoDMY(s) {
var b = s.split(/\D/);
return b[2] + '.' + b[1] + '.' + b[0];
}
console.log(formatYMDtoDMY('2017-10-01 23:12:12'))
Note however that dates should use unambiguous formats like DD-MMM-YYYY, e.g. 01-Jan-2017. It only takes one more line of code for that. ;-)
Don't forget, getMonth() returns a Number, from 0 to 11, representing the month,
and Date make the date as object with methods and properties
There is a lot of examples here
var date = new Date('2010-10-11 00:00:00');
var formatDate = date.getDate() + '/'
+ (date.getMonth() + 1) + '/'
+ date.getFullYear();
console.log( formatDate );
So you can always pass the date on any format but there some important moments you can read here:
Converting string to date in js
Are you asking?
I don't know how to go from the beginning.
You could get the beginning from current month and the last date of next month by following code:
<html>
<script>
var myDate = new Date();
var thisMonth = new Date(myDate.getFullYear(), myDate.getMonth(), 1);
var nextMonth = new Date(myDate.getFullYear(), myDate.getMonth() + 2, 0);
console.log("Date start: " + thisMonth);
console.log("Date end: " + nextMonth);
console.log("Formatted date start: " + formatDate(thisMonth));
console.log("Formatted date end: " + formatDate(nextMonth));
function padLeft(n){
return ("00" + n).slice(-2);
}
function formatDate(){
var d = new Date,
dformat = [ d.getFullYear(),
padLeft(d.getMonth()+1),
padLeft(d.getDate())
].join('-')+
' ' +
[ padLeft(d.getHours()),
padLeft(d.getMinutes()),
padLeft(d.getSeconds())].join(':');
return dformat
}
</script>
</html>
I hope it helps you. Bye.

Converting string to date object, adding two hours and converting back to string (JavaScript)

I have a date string, want to convert it into a date object, add 2 hours and print out the converted date object back to a variable. But I get the error listed bellow:
// dateTime: 2013-09-27 09:50:05
var dateTime = $("#inputDatetime").val();
var startDate = dateTime;
var date = new Date(startDate);
var duration = 2;
var endDate = date;
endDate.setHours(date.getHours()+duration)
var dateString = endDate.format("dd-m-yy hh:mm:ss");
Error:
Uncaught TypeError: Object [object Date] has no method 'format'
Why do I get this TypeError?
Vaibs,
there is no method "format", you can do formating using available methods from Date Object.
please don't use plugin
example :
// dd-mm-yy hh:mm:ss
function formatDate(date) {
return ((date.getDate()<10?'0':'')+date.getDate()) + "-"+
(((date.getMonth()+1)<10?'0':'') + (date.getMonth()+1)) + "-" +
date.getFullYear() + " " +((date.getHours()<10?'0':'')+date.getHours()) + ":" +
(date.getMinutes()<10?'0':'') + date.getMinutes() + ":" +
(date.getSeconds()<10?'0':'') + date.getSeconds();
}
*thank you #donot
Use jquery ui date parser.
http://docs.jquery.com/UI/Datepicker/parseDate
This is the best function for parsing dates out of strings that I've had the pleasure to work with in js. And as you added the tag jquery it's probably the best solution for you.
.format() is not a valid Date method. JavaScript does not have an easy way to format dates and times with a user-specified format. The best you can do (without separate plugins) is to create your own string by getting each component of the date separately, and formatting/concatenating them.
I've used this before and it seems to work!
var dateString = endDate.toString("dd-m-yy hh:mm:ss");

Categories

Resources