I'm a bit of a rambler, but I'll try to keep this clear -
I'm bored, so I'm working on a "shoutbox", and I'm a little confused over one thing. I want to get the time that a message is entered, and I want to make sure I'm getting the server time, or at least make sure I'm not getting the local time of the user. I know it doesn't matter, since this thing won't be used by anyone besides me, but I want to be thorough. I've looked around and tested a few things, and I think the only way to do this is to get the milliseconds since January 1, 1970 00:00:00 UTC, since that'd be the same for everyone.
I'm doing that like so:
var time = new Date();
var time = time.getTime();
That returns a number like 1294862756114.
Is there a way to convert 1294862756114 to a more readable date, like DD/MM/YYYY HH:MM:SS?
So, basically, I'm looking for JavaScript's equivalent of PHP's date(); function.
var time = new Date().getTime(); // get your number
var date = new Date(time); // create Date object
console.log(date.toString()); // result: Wed Jan 12 2011 12:42:46 GMT-0800 (PST)
If you want custom formatting for your date I offer a simple function for it:
var now = new Date;
console.log( now.customFormat( "#DD#/#MM#/#YYYY# #hh#:#mm#:#ss#" ) );
Here are the tokens supported:
token: description: example:
#YYYY# 4-digit year 1999
#YY# 2-digit year 99
#MMMM# full month name February
#MMM# 3-letter month name Feb
#MM# 2-digit month number 02
#M# month number 2
#DDDD# full weekday name Wednesday
#DDD# 3-letter weekday name Wed
#DD# 2-digit day number 09
#D# day number 9
#th# day ordinal suffix nd
#hhhh# 2-digit 24-based hour 17
#hhh# military/24-based hour 17
#hh# 2-digit hour 05
#h# hour 5
#mm# 2-digit minute 07
#m# minute 7
#ss# 2-digit second 09
#s# second 9
#ampm# "am" or "pm" pm
#AMPM# "AM" or "PM" PM
And here's the code:
//*** This code is copyright 2002-2016 by Gavin Kistner, !#phrogz.net
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
Date.prototype.customFormat = function(formatString){
var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhhh,hhh,hh,h,mm,m,ss,s,ampm,AMPM,dMod,th;
YY = ((YYYY=this.getFullYear())+"").slice(-2);
MM = (M=this.getMonth()+1)<10?('0'+M):M;
MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substring(0,3);
DD = (D=this.getDate())<10?('0'+D):D;
DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getDay()]).substring(0,3);
th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);
h=(hhh=this.getHours());
if (h==0) h=24;
if (h>12) h-=12;
hh = h<10?('0'+h):h;
hhhh = hhh<10?('0'+hhh):hhh;
AMPM=(ampm=hhh<12?'am':'pm').toUpperCase();
mm=(m=this.getMinutes())<10?('0'+m):m;
ss=(s=this.getSeconds())<10?('0'+s):s;
return formatString.replace("#hhhh#",hhhh).replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm).replace("#AMPM#",AMPM);
};
You can simply us the Datejs library in order to convert the date to your desired format.
I've run couples of test and it works.
Below is a snippet illustrating how you can achieve that:
var d = new Date(1469433907836);
d.toLocaleString(); // expected output: "7/25/2016, 1:35:07 PM"
d.toLocaleDateString(); // expected output: "7/25/2016"
d.toDateString(); // expected output: "Mon Jul 25 2016"
d.toTimeString(); // expected output: "13:35:07 GMT+0530 (India Standard Time)"
d.toLocaleTimeString(); // expected output: "1:35:07 PM"
Below is a snippet to enable you format the date to a desirable output:
var time = new Date();
var time = time.getTime();
var theyear = time.getFullYear();
var themonth = time.getMonth() + 1;
var thetoday = time.getDate();
document.write("The date is: ");
document.write(theyear + "/" + themonth + "/" + thetoday);
Try using this code:
var datetime = 1383066000000; // anything
var date = new Date(datetime);
var options = {
year: 'numeric', month: 'numeric', day: 'numeric',
};
var result = date.toLocaleDateString('en', options); // 10/29/2013
See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
Try using this code:
var milisegundos = parseInt(data.replace("/Date(", "").replace(")/", ""));
var newDate = new Date(milisegundos).toLocaleDateString("en-UE");
Enjoy it!
so you need to pass that var time after getTime() into another new Date()
here is my example:
var time = new Date()
var time = time.getTime()
var newTime = new Date(time)
console.log(newTime)
//Wed Oct 20 2021 15:21:12 GMT+0530 (India Standard Time)
here output is my datetime standard format for you it will be in country format
if you want it in another format then you can apply another date function on var newTime
like
var newTime = new Date(time).toDateString()
console.log(newTime)
//Wed Oct 20 2021
Try this one :
var time = new Date().toJSON();
One line code.
var date = new Date(new Date().getTime());
or
var date = new Date(1584120305684);
/Date(1383066000000)/
function convertDate(data) {
var getdate = parseInt(data.replace("/Date(", "").replace(")/", ""));
var ConvDate= new Date(getdate);
return ConvDate.getDate() + "/" + ConvDate.getMonth() + "/" + ConvDate.getFullYear();
}
Assume the date as milliseconds date is 1526813885836, so you can access the date as string with this sample code:
console.log(new Date(1526813885836).toString());
For clearness see below code:
const theTime = new Date(1526813885836);
console.log(theTime.toString());
use datejs
new Date().toString('yyyy-MM-d-h-mm-ss');
Related
I have read several questions on stack overflow and all over the internet but somehow I am unable to get it right. I get a date from another function and the value is as below.
var currentDate = new Date("2021-04-27T15:30:27.588+0000");
console.log(currentDate); // this prints Wed Apr 28 2021 00:00:00 GMT+1000 (Australian Eastern Standard Time)
// want to add 45 days to my date
var offset = 45;
var xDate = new Date();
xDate.setDate(currentDate.getDate() + offset);
console.log(xDate);
The output I get is:
Mon Jul 12 2021 19:00:57 GMT+1000 (Australian Eastern Standard Time)
where as this should be some date in June.
Please can someone help me understand what I am doing wrong?
The problem is that when you are initializing a new date object using new Date(), the date object is initialized with the current date. When you increment the days using currentDate.getDate() + offset the day of the month is first set to that of currentDate and incremented by offset but the month from which it is incremented is the current month. Try this one.
var currentDate = new Date("2021-04-27T15:30:27.588+0000");
console.log(currentDate); // this prints Wed Apr 28 2021 00:00:00 GMT+1000 (Australian Eastern Standard Time)
// want to add 45 days to my date
var offset = 45;
var xDate = new Date("2021-04-27T15:30:27.588+0000");
xDate.setDate(currentDate.getDate() + offset);
console.log(xDate);
1 day is equal to 86,400,000 milliseconds. You can multiply that value by 45 and add it to your date:
var currentDate = new Date("2021-04-27T15:30:27.588+0000");
console.log(currentDate);
// Add 45 days
var offset = 45;
var xDate = new Date(currentDate.getTime() + offset * 86400000);
console.log(xDate);
My suggestion:
const addDays = (date, days) => {
var ndt = new Date(date);
ndt.setDate(date.getDate() + days);
return ndt;
};
var date = new Date("2021-04-27T15:30:27.588+0000");
console.log(date);
console.log(addDays(date, 45));
I agree Wais Kamal's answer is right. The below code is more succinct since you avoid time calculations
var currentDate = new Date("2021-04-27T15:30:27.588+0000");
var offset = 45;
var xDate = currentDate.setDate(currentDate.getDate() + offset);
console.log(xDate);
You can make use of the moment here. Link to official docs. Don't forget to install moment package like so (assuming you are using npm)
npm i moment
const myDate = "2021-04-27T15:30:27.588+0000";
const updatedDate = moment
.utc(myDate)
.add(45, 'days')
.format('YYYY-MM-DD');
console.log('updatedDate', updatedDate); // "2021-06-11"
I need date and time in this format in javascript.
2016/02/17-14:31:36
Currently I am using
var data = new Date();
But this gives Date {Fri Feb 26 2016 18:38:45 GMT+0530 (India Standard Time)}
var d = new Date(),
year = d.getFullYear(),
month = ('0'+(d.getMonth()+1)).slice(-2),
day = ('0'+d.getDay()).slice(-2),
hour = ('0'+d.getHours()).slice(-2),
minute = ('0'+d.getMinutes()).slice(-2),
second = ('0'+d.getSeconds()).slice(-2);
var dateString = year+'/'+month+'/'+day+'-'+hour+':'+minute+':'+second;
Next time, please google yourself. Thanks.
Edit
Now it also has those leading zero's.
I'm working with a string of data in this format: "mm-dd-yy". I convert this to a Date object in this way:
var dateData, dateObject, dateReadable, dateSplit, year, month, day;
dateData = "07-21-14"; //For example
dateSplit = dateData.split('-');
month = dateSplit[0] - 1;
day = dateSplit[1];
year = 20 + dateSplit[2];
dateObject = new Date(year, month, day);
dateReadable = dateObject.toUTCString(); //Returns Mon, 21 Jul 2014 04:00:00 GMT
I would like to return the date (Mon, 21 Jul 2014) without the time (04:00:00 GMT). Is there a different method that will do so? Or a way of calling .toUTCString() to return the date without the time?
I believe you want .toDateString() or .toLocaleDateString()
http://www.w3schools.com/jsref/jsref_todatestring.asp
In fact, you should also look at Date.parse():
var dateData, dateObject, dateReadable;
dateData = "07-21-14"; //For example
dateObject = new Date(Date.parse(dateData));
dateReadable = dateObject.toDateString();
Please advise:
Is there a way without regex or string replaces and so forth to convert a simple date such as:
Fri Jun 21 00:00:00 UTC+0100 2013
To a ISO8601 formatted date yy-mm-dd?
PS: 8601 date only, not date time.
Use moment.js http://momentjs.com/
moment(new Date(), "YYYY-MM-DD HH:mm Z");
or:
var date = moment("Fri Jun 21 00:00:00 UTC+0100 2013");
moment("Fri Jun 21 00:00:00 UTC+0100 2013", "YYYY-MM-DD HH:mm Z");
You can parse it and format it very easily whatever way you want http://momentjs.com/docs/ it is compatible with ISO-8601 dates for parsing as well.
Yes !
the date function in javascript.
var d = new Date("Fri Jun 21 00:00:00 UTC+0100 2013")
alert( d.getFullYear() + '-' + d.getUTCMonth() + '-' + d.getUTCDay())
2 lines of code :)
more info here : http://www.w3schools.com/jsref/jsref_obj_date.asp
Without regexes or string replaces? Yes, assuming that the format is fixed you could use .slice() and/or .substr() to extract the particular bits you need and rearrange them (unless such methods fall into your category of "and so forth"):
var input = "Fri Jun 21 00:00:00 UTC+0100 2013";
var year = input.slice(-4),
month = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'].indexOf(input.substr(4,3))+1,
day = input.substr(8,2);
var output = year + '-' + (month<10?'0':'') + month + '-' + day;
Or you could go ahead and get silly with a regex replace:
var output = input.replace(/^[^\s]+\s([^\s]+)\s(\d+)\s.*(\d{4})$/,function(m,p1,p2,p3) {
var month = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'].indexOf(p1)+1;
return p3 + '-' + (month<10?'0':'') + month + '-' + (p2.length===1?'0':'') + p2;
});
Of course you'd probably want to wrap such code in a reformatDate() method.
(For a "simple" reformatting of a date string, the Date object and its methods aren't particularly helpful unless the starting format is one recognised by Date.parse().)
Why dont you try to use the get functions, like getDate(), getMonth(), etc. For example:
var today = new Date();
var d1 = new Date();
alert(d1);
var date = d1.getDate();
var month = d1.getMonth() + 1;
var year = d1.getFullYear();
Then configure the string the way you want it to appear...!
I tried many times to convert utc datetime to local datetime,and I have failed. My utc datetime format is
Fri Mar 8 23:12:27 UTC+0200 2013
Also my JavaScript code is
var time = Date(param_time);//param_time is /Date(1362866006646)/
And then time is being Sun Mar 10 00:21:54 UTC+0200 2013 I need to datetime as 2008-01-28T20:24:17Z because I will convert local datetime to pretty datetime.
http://ejohn.org/files/pretty.js
How can I do this ? I looked at many questions on stackoverflow but no one does it work. Thank you.
In order to format your Date correctly use toISOString():
var time = param_time.toISOString();
Note that param_time needs to be a valid Date object.
References
MDN: Date (sections: Syntax, Example: ISO 8601 formatted dates)
I rarely use javascript and all this date time conversion are mystery to me as well, javascript is a client side technology and all this "UTC" phrases means nothing (at least to me), as all the kind of getUTC...()/setUTC...() functions works in local time, the same is goes for all Date.to...String() functions, even the new Date() (that due to the docs) s'd be initialized in UTC, also give a local time.
However, if you have a (correct) date in UTC and wish to convert it to current (client side) local time, then you need getTimezoneOffset(), or shortly:
function UTCToLocalTime(d) {
var timeOffset = -((new Date()).getTimezoneOffset()/60);
d.setHours(d.getHours() + timeOffset);
return d;
}
var time = new Date(Date.parse('Fri Mar 8 23:12:27 UTC+0200 2013'));
alert(UTCToLocalTime(time)); // Sat Mar 9 01:12:27 UTC+0200 2013
//p.s. or...
function UTCToLocalTime2(d)
{
return new Date(d.toString().replace(/UTC.*/g,"") + d.getYear());
}
var timezone = "UTC+01:30";
var start = new Date();
if(timezone != "UTC"){
timezone = timezone.replace(/UTC/g,"");
znak = timezone.charAt(0);
timezone = timezone.replace(/[+|-]/g,"");
timezone = timezone.split(":");
//var start = new Date(start.toString() + " " + timezone);e.
//alert(start.toString());
if(znak == "+") start = new Date(start.getTime() + (timezone[0]*60*60000 + timezone[1] * 60000) );
if(znak == "-") start = new Date(start.getTime() - (timezone[0]*60*60000 + timezone[1] * 60000) );
}
var hours = start.getUTCHours();
var minutes = start.getUTCMinutes();
var seconds = start.getUTCSeconds();
var day = 10;
var month = 04;
var year = 2015;
var dateUtc = Date.UTC(year, month - 1, day + 1, 0, 0, 0);
> 1428710400000
var toDate = new Date(dateUtc);
> Fri Apr 10 2015 21:00:00 GMT-0300 (Hora oficial do Brasil)