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'));
Related
I need to get the current date in Vue.js.
For that, I used the following method.
today_date: new Date().toJSON().slice(0,10).replace(/-/g,'.')
today_date will give the date as 2019.09.11 format.
Is there any method to customize this format? Actually I need to get the date as 11.09.2019 format. But it's better to know whether there are solutions to get the date in several formats.
In pure Javascript you should hard code the format that you want by getting the day, month and year, and concatenate them to get what you want, but i recommend to use the moment.js library to format the date easily like :
moment().format('MMMM Do YYYY, h:mm:ss a'); // September 11th 2019, 10:52:10 am
moment().format('dddd'); // Wednesday
moment().format("MMM Do YY"); // Sep 11th 19
moment().format('YYYY [escaped] YYYY');
Can be done in different ways One brilliant lib: MomentJS (which can take care of a lot of formats, locales and operations too), but one solution using pure JS could be:
function dtFormatter(d) {
const yr = d.getFullYear();
const mnt =
d.getMonth() + 1 < 9 ? "0" + (d.getMonth() + 1) : d.getMonth() + 1;
const day = d.getDate() < 9 ? "0" + d.getDate() : d.getDate();
return day + "." + mnt + "." + yr;
}
console.log(dtFormatter(new Date()));
I am updated the value of an HTML input field with data from a query:
$("##warranty_end_date#id#").val(warranty_end_date);
But the data is store in my database as a SQL Date/Time and has an output like this: May, 08 2019 00:00:00 -0400
I would like the data to be formatted like this: 05/08/2016
How can I accomplish this?
warranty_end_date = "May, 08 2019 00:00:00 -0400";
var d = new Date(warranty_end_date);
var f = ("00" + (d.getDate()).toString()).slice(-2) + "/" + ("00" + (d.getMonth()+1).toString()).slice(-2) + "/" + (1900 + d.getYear()).toString();
$("##warranty_end_date#id#").val(f);
Maybe you could format the date in the SQL query already.
Something like:
SELECT convert(varchar, getdate(), 101)
101 = mm/dd/yyyy – 10/02/2008
var date = new Date('2010-10-11T00:00:00+05:30');
alert((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
You can accomplish this using the following:
var date = new Date('May, 08 2019 00:00:00 -0400');
var output = date.toLocaleFormat('%m/%d/%Y');
alert(output);
Here's a jsfiddle: https://jsfiddle.net/y4zemzqg/
Also, look over using moment.js. http://momentjs.com/ Moment.js makes formatting dates and time incredibly easy. I've used it for quite some time with no issue:
var theDate = moment('May, 08 2019 00:00:00 -0400').format('MM/DD/YYYY');
alert(theDate);
Here is a JS Fiddle using the moment.js solution: https://jsfiddle.net/v923bn5s/
I have a time/date string that is returned like so:
"5/31/2016, 2:23:33 PM". I need only the HH:MM and am/pm, so 2:23 PM
I am able to split the date off but not sure how I can remove the colon and seconds.
time = time.split(",")[0];
//time = " 2:23:33 PM";
thanks
If starting with a date/time string and desiring to end with a time string, of the same format, consider the following regular expression with two capture groups:
var dateStr = "5/31/2016, 2:23:33 pm";
var m = dateStr.match(/(\d{1,2}:\d{2}):\d{2}\s+?(AM|PM)/i)
// ^-- 1 ^-- 2
if (m) {
console.log(m[1] + " " + m[2].toUpperCase()); // "2:23 PM"
}
Otherwise, if ever needing to deal with a proper date/time object I'd consider moment.js - and specify the appropriate conversion format.
I would not use new Date(nonISO8601String) for parsing as it is unreliable across browsers/localizations.
I suggest using moment.js to parse the string and then output as a formatted string like this
var input = "5/31/2016, 2:23:33 PM";
var result = moment(input);
console.log(result.format("hh:mm a"));
//output: 02:23 pm
Fiddle
Update
As others have mentioned, although this answer does work as expected, that may not be the case across all browsers and locales the same.
My recommendation would preferably to use one of the popular date libraries like Moment.js, which could be argued as the de facto standard at the present time for handling this.
Using a Date Object
While this is entirely feasible through a series of splits, regular expressions, etc, it may simply be easier to just use some of Javascript's built-in Date functionality (assuming that your format isn't going to vary wildly).
You could consider writing a function to parse your date as a Date object and then formatting it accordingly :
function formatDateStringAsTime(input){
var date = new Date(input);
// Determine if it is AM or PM
var ampm = date.getHours() >= 12 ? ' PM' : ' AM';
// Output what you need
return (date.getHours() % 12) + ':' + date.getMinutes() + ampm;
}
Additionally if you want to ensure you have two digits (i.e. zero padded values), you can use a bit of slicing to change that :
// Using this approach will pad your hours and minutes with zeros if necessary
return ('0' + (date.getHours() % 12)).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2) + ampm;
Example
formatDateStringAsTime("5/31/2016, 2:23:33 PM"); // yields 2:23 PM
var input = "5/31/2016, 2:03:33 PM";
input = formatDateStringAsTime(input);
console.log(input);
function formatDateStringAsTime(input) {
var date = new Date(input);
// Determine if it is AM or PM
var ampm = date.getHours() >= 12 ? ' PM' : ' AM';
return ('0' + (date.getHours() % 12)).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2) + ampm;
}
Consider Date-specific Libraries
As others have mentioned, if you are going to be performing this behavior frequently within your application, you might consider using a library like Date.js or Moment.js, which are designed for exactly this.
You can do it in two lines using this regex:
var a = new Date("5/31/2016, 2:23:33 PM");
var b = a.toLocaleTimeString().replace(/:\d{2}\s/,' ');
console.log(b)
Parsing of strings using the Date constructor (and Date.parse) is largely implementation dependent and inconsistent across browsers so should not be relied upon. If parsing is required, use a bespoke function or library, there are plenty to choose from.
But reformatting a string doesn't require parsing, just extracting the required values. There are any number of simple ways to manipulate the string, here are two (note that leading zeros for hours are typically only used for 24 hour time formats):
// Extract h:mm ap component of a string in m/d/y h:mm:ss ap format
function getTime(s) {
var b = s.split(/\D/);
function z(n){return (n<10?'0':'')+n}
return z(b[4]) + ':' + z(b[5]) + ' ' + s.slice(-2);
}
document.write(getTime('5/31/2016, 2:23:33 PM'));
And (though this doesn't add leading zeros):
document.write(
'5/31/2016, 2:23:33 PM'.replace(/[^\s]*,\s|:\d+\s/g,' ').trim()
);
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.
can someone help me with a javascript regex question?
I am trying to replace all the digit dates in a string to a formatted version.
This is what I have so far
txt = txt.replace(/\d{10}/g, 'Formatted Date Here');
Is this possible? Any help is greatly appreciated! Thanks!
Try this:
str = str.replace(/\d{10}/g, function($0) {
return new Date($0*1000);
});
Date accepts a time in milliseconds. That’s why you multiply the match (passed in $0) with 1000.
If you want a different format than the default format, take a look at the methods of a Date instance. Here’s an example:
str = str.replace(/\d{10}/g, function($0) {
var d = new Date($0*1000);
return (d.getMonth() + 1) + ", " + d.getDate() + ", " + (d.getHours() % 12 || 12) + ":" + d.getMinutes() + " " + (d.getHours() < 12 ? 'AM' : 'PM');
});
The JavaScript Date.format functon Amarghosh posted here might help you.
You can use replace() with a function callback to achieve this:
var txt = "This is a test of 1234567890 and 1231231233 date conversion";
txt = txt.replace(/\d{10}/g, function(s) {
return new Date(s * 1000);
});
alert(txt);
outputs:
This is a test of Sat Feb 14 2009 07:31:30 GMT+0800 and Tue Jan 06 2009 16:40:33 GMT+0800 date conversion
You will need to adjust this to use the correct date format. Also you will need to consider the issue of time zones. The time zone on the client isn't necessarily the same as that on the server.
You might even be better off formatting the date on the server to avoid such issues.
Are you sure you want to use regex? Here is a JavaScript Date format function that you might want to check out.