javascript get current datetime - javascript

Good evening,
I am writing server application that will be running on node websocket and im having hard time processing dates.
This is piece of code that i wrote:
var getDatetime = function() {
var checkLength = function(part) {
return (part < 10) ? '0' + part : part;
};
var date = new Date(),
year = date.getFullYear(),
month = checkLength(date.getMonth()),
day = checkLength(date.getDay()),
hour = checkLength(date.getHours()),
minute = checkLength(date.getMinutes()),
second = checkLength(date.getSeconds());
return day + '-' + month + '-' + year + ' ' + hour + ':' + minute + ':' + second;
};
It pains me to use it like that, im no pro with js so im asking, is there a method like in php date('d-m-Y H:i:s', time()) with which you can get current datetime in nice and clean way instead of doing this the way i showed?

I would recommend Moment.js. It can be deployed both on front end and nodejs server. Here's the install instruction for nodejs.

With the Javascript constructor, date(), under the Conversion getter section of the page linked to, there are several options for converting the format such as date.doDateString(). This will create a human-readable string, and with it being a string it can be cut up and re-arranged as needed with the use of sub strings.
var a = new Date();
console.log(a); // Wed March 25th 2015 16:10:38GMT -0700 (Pacific Daylight Time)
With AngularJS you have an easy way to show dates which are in the epoch function, with the date filter.

Related

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.

Formatting a date from Date.parse(dateString) in another format

Currently I am making a rest call to SharePoint using JavaScript Rest API. I am getting a Modified date which comes in the following format "2016-08-27T17:40:09Z", from what I have been reading this is a problem many developers have a problem with.
So I decided to go ahead and use the Date.parse(dateString) method to convert the quirky date format and now I am getting Sat Aug 27 2016 13:40:09 GMT-0400 (Eastern Daylight Time).
Now this is something that can be understood, however I am not looking for this, I am looking for the following format Month\Date\Year Hour:Minute. I have been reading the documentation but I am not found anything yet.
var d = new Date('2016-08-27T17:40:09Z'),
dFormatted = [d.getMonth() + 1, d.getDate(), d.getFullYear()].join('\\') + ' ' + [d.getHours(), d.getMinutes()].join(':');
console.log(dFormatted);
If your format is very unique then you need to make your own formatter:
function toMyFormat(time) {
var d = new Date(time);
return d.getMonth() + '\\' + d.getDate() + '\\' + d.getFullYear() + ' ' + d.getHours() + ':' + d.getMinutes();
}
console.log(toMyFormat('2016-08-27T17:40:09Z'));
You may however be lucky enough to find a localeString format that suits you:
var d = new Date('2016-08-27T17:40:09Z');
console.log(d.toLocaleString('en-US'));
console.log(d.toLocaleString('da-DK'));
console.log(d.toLocaleString('de-GE'));

new date() AngularJS time sent from a server GMT to your local computer

I get a response from a service and when the service returns it returns with a created server GMT date. The issue arises when I want to display the local date ex: 5-22-2016 I want to change the time to my local computer.
my response looks something like this:
createdDate: "2016-04-22 16:48 PM GMT"
description: "File Upload Success"
fileGuid:"62e7250c-d5ed-41e2-b5b2-4600094d9a7c"
fileSize:"191429"
There are 90 different objects in my array.
I am trying to use _each which iterates through all of my key value pairs:
_.each(data, function(value, key) {
console.log(key, value);
var strDateTime = value.createdDate;
var myDate = new Date(strDateTime);
data[key].createdDate = (myDate.toLocaleString()).split(',')[0];
console.log("data", data)
But it is working for some of created dates and the others are returning invalid any suggestions
According to ECMA-262 5.1 15.9.1.15 Date Time String Format, seems some of your data doesn't in the right format.
ECMAScript defines a string interchange format for date-times based upon a simplification of the ISO 8601 Extended Format. The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ.
So a better solution would be using the moment.js.
With moment.js you can update your code into,
moment('2016-5-5').toLocaleString() //'Tue May 05 2015 00:00:00 GMT+0800'
Also, for only the showing purpose, there is an angular directive version, angular-moment.
Hope this would help. :)
Thx for the notice from #RobG, I just replaced the MDN with ECMA-262.
and for moment("2016-04-22 16:48 PM GMT"), you can see from the picture below,
You should manually parse date strings. A library can help, but if you only have one format, a bespoke parsing function is fairly trivial.
If the dates are always GMT and in the format '2016-04-22 16:48 PM GMT', a function like the following may suit.
If you want the output string in a particular format, you can use toISOString, which returns a string in ISO 8601 format with GMT time zone, or you can write a small formatting function to generate the format you require.
var s = '2016-04-22 16:48 PM GMT';
// Return a Date given a string in format 2016-04-22 16:48 PM GMT
function parseSpecial(s) {
var b = s.split(/[-\s:]/);
var h = (b[3]%12) + (/pm/i.test(s)? 12: 0);
return new Date(Date.UTC(b[0], b[1]-1, b[2], h, b[4]));
}
// Return a string in format mm/dd/yyyy hh:ss a given a date
function myFormat(date) {
function z(n){return (n<10?'0':'') + n}
var h = date.getHours();
var ap = h > 11? 'pm' : 'am';
h = h%12 || 12;
return z(date.getMonth() + 1) + '/' + z(date.getDate()) + '/' +
date.getFullYear() + ' ' + z(h) + ':' + z(date.getMinutes()) +
' ' + ap;
}
var d = parseSpecial(s);
document.write(s + // Original string
'<br>' + d.toISOString() + // As ISO 9601 long format string
'<br>' + myFormat(d) // As local date and time
+ ' (your local date and time equivalent)');
You an use a library to do all of the above, but whether one is necessary or not is up to you. For example, using moment.js, you'd do:
// Parse the string, passing the format
var s = '2016-04-22 16:48 PM GMT';
var d = moment(s.replace('GMT','Z'), 'YYYY-MM-DD hh:mm a Z');
// Create a string for local time in the required format
console.log(d.format('DD/MM/YYYY hh:mm a'));

Converting a date in an invalid javascript format to an ics standard datetime field

The date and time are actually separate in the data I have however I thought combining them would be the ideal solution?
The unaltered data looks like the following:
2014/09/04 and 02:30PM
var aDate = new Date('2014/09/04 02:30PM');
//Invalid date....
console.log(aDate.toString());
Needs to convert to the date that .ics files use which looks like:
20140904T023000 --> This is what the above date would turn into.
How do I do this?
JSBin you could test in...
Change
var aDate = new Date('2014/09/04 02:30PM');
to
var aDate = new Date('2014/09/04 02:30 pm');
and it should work. You just need to put in a SPACE before PM. This will not give you invalid date error. Then you can use that date to get ICS format.
Here is the logic to get ICS format. I know this is not as efficient, but tried to keep it simple.
var pre =
aDate.getFullYear().toString() +
((aDate.getMonth() + 1)<10? "0" + (aDate.getMonth() + 1).toString():(aDate.getMonth() + 1).toString()) +
((aDate.getDate() + 1)<10? "0" + aDate.getDate().toString():aDate.getDate().toString());
var post = (aDate.getHours()%12).toString() + aDate.getMinutes().toString() + "00";
console.log(pre + "T" + post);
You should be able to parse the date fine if you use 24 hour notation for time rather than denoting AM/PM.
From Chrome console:
(new Date('2014/09/04 02:30PM'));
Invalid Date
(new Date('2014/09/04 14:30'));
Thu Sep 04 2014 14:30:00 GMT+0100 (BST)
With this object, you should be able to construct the ICS format compliant date you require using the various getters on the Date prototype.
There are no default api`s to convert to .ics file format, you can however do it manually.
function toITCFormat(date, time)
{
var timeCont = [],
dateCont = [];
if(time.toLowerCase().indexOf('pm')!=-1)
{
timeCont = time.toLowerCase().replace('pm',00).split(':'); //assuming from your question seconds is never mentioned but only hh:mm i.e. hours and minutes
timeCont[0] = (parseInt(timeCont[0])+12)%24;
}
else
{
timeCont = time.toLowerCase().replace('am',00).split(':');
}
dateCont = date.split('/');
return dateCont.join('')+'T'+timeCont.join('');
}
var x = toITCFormat('2014/09/04','02:30PM');
console.log(x);// this will output ur .ics format
JSFiddle Example

Making a basic date(technical)

NO JQUERY! I have a drop down in which the user selects a day month and year. I create the following code and pass these values into the variable using setFullYear. At times I also add days to this variable which is waht the variable ev_num is for. When I write this to the page it displays a lot of unnecessary info...
Sat Jan 01 2011 11:44:26 GMT-0500 (Eastern Standard Time)
I want it to simply read 'Jan 01 2011' or something like that. Does anyone know how I would fix this. Here is a jsfiddle of the entire page... http://jsfiddle.net/fET6v/
var myDate=new Date();
var ev_num = parseInt(document.getElementById("leave").value)
myDate.setFullYear(sel_year.value,sel_month.value,sel_day.value);
var event_value = document.getElementById("leave").value;
var d = new Date();
var day = d.getDate();
var year = d.getFullYear();
var month = d.getMonth();
var months=["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct"," Nov","Dec"];
var currentMonth = months[month];
document.write(currentMonth + " " + day + " " + year);
This will print today's date with abbreviated months. It's fully customizable.
http://jsfiddle.net/iansan5653/u7hkE/
EDIT: See this demo for the leading zero in front of the day number: http://jsfiddle.net/iansan5653/u7hkE/1/
If you don't want the time and timezone to appear, use the .toDateString method instead of the simple toString. If you want a custom format, you will need to build the string yourself, you can get the single year/month/date values with the respective methods from your Date object. There are some (googlable) libraries to do that, a single method for your case would be
function myDateString(date) {
return ["Jan","Feb","Mar", …][date.getMonth()] +
" "+("0"+date.getDate()).substr(-2) +
" "+date.getFullYear();
}
http://blog.stevenlevithan.com/archives/date-time-format

Categories

Resources