Date format conversion javascript - javascript

Consider if we have a date in the format Sat Jul 28 2012 , is there a general a function to convert it in to any wanted format??
say for example 28-07-2012,
deciding the separators like - or /

Javascript's Date object has lots of different versions of toString and different getters, so it should be pretty easy to get the output you want. Scroll down through this documentation to see some of your options. They have pretty good examples too if you click on them.
In addition, the Date constructor is fairly good at taking in most strings and converting it.
var myDate = new Date("Sat Jul 28 2012");
alert(myDate.toLocaleDateString());
Or use the different getters and string concatenation wrapped in a function to make your own.

You can write a function to do it, i dont think there is a Native method:
function convert(dateObj) {
var format = dateObj.getFullYear()+"-";
format += dateObj.getMonth()+"-";
format += dateObj.getDate();
return format;
}
you can customize it however you want. here is the list of methods for the date object

Javascript only outputs it into the standard format you provided above. You can try using the getDate(), getDay(), getMonth() methods (among others) to extract the necessary data and convert it to your liking.
Please refer to W3Schools' description of the JavaScript Date object.

Related

Convert JavaScript Date to formatted String

I have a JavaScript Date object and want to convert it into String like this:
2018-05-24T11:00:00+02:00
var dateObj = new Date("Thu May 24 2018 11:00:00 GMT+0200");
function convertToString(dateObj) {
// converting ...
return "2018-05-24T11:00:00+02:00";
}
You can use moment.js, it handles pretty much all the needs about date formatting you may have.
var dateObj = new Date("Thu May 24 2018 11:00:00 GMT+0200");
console.log(moment(dateObj).format())
You have quite the options to represent the DateTime object as a string. This question was already elaborated on in the following StackOverflow answers:
Using toLocaleDateString()
Using dateFormat library (requires the use of external library)
Vanilla JavaScript, adds a few extra lines, but the format is entirely up to you
Personally, I would sacrifice a few extra lines in my document for the Vanilla JavaScript variant. This way I would have complete control of the format and of the function responsible for the formatting - easier debugging and future changes. In your case that would be (using string literals to shorten the code):
var date = new Date("Thu May 24 2018 11:00:00 GMT+0200");
function convertToString(date) {
return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}-...`;
}
And so on. On this page Date - JavaScript | MDN, in the left you have all the methods that extract some kind of information from the Date object. Use them as you wish and you can achieve any format you desire. Good luck!

JavaScript Date subtracting 4 hours

I have a JavaScript function that compares 2 dates. I am trying to format the dates properly but the Date is subtracting 4 hours (presumably to compensate for GMT and EST), unnecessarily.
$.each(json.data, function(i, v) {
$.each(zoneObj, function(k, z) {
if (v.ptid == z.ptid) {
console.log(v.timeStamp);
var d = new Date(v.timeStamp);
console.log("datTime " + d);
Result
I see that Date is converting the v.timeStamp to Easter Standard but that isn't necessary. How do I disable this?
I need to use Date in order to take advantage of the getMonth, getMinute, etc. methods
Most of the methods for the Date object will use the local time which in your case is Eastern Standard Time. If you want to use UTC, you need to specify those methods explicitly.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
You can get UTC values of the standard JS Date object.
The functions are: getUTCMilliseconds(), getUTCSeconds(), getUTCMinutes(), getUTCHours(), getUTCFullYear(), getUTCDay() and getUTCDate()
Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
But I would suggest you to use moment.js, which is far more powerful than standard JS Date and it is used by everyone.
Read more here: http://momentjs.com

javascript timezone format

I need to format a javascript Date to send via json to the server. The server expects the time to be in the format according to this example
2011-08-31T06:49:28.931 -0700
which it conveniently tells me when I try to submit something like
2011-08-31T06:49:28.931 -07:00
The trouble I am having is with the timezone part, -0700. I've been looking at the Date API, and don't see a way to specify the timezone format. I can do d.getTimezoneOffset, but it returns 240 (Im in EDT I think) for me.
So, I can convert 240 to 0400 to represent 4 hours. I am worried however about correctness for other timezones. My questions are
1) How to convert the result of the getTimezoneOffset() into the required format, and how to determine what the sign should be (thats the part I am worried about)?
2) Is there a way to get the format off the date object itself so I don't have to do anything custom? If i do d.toString() I get "Wed Aug 31 2011 09:48:27 GMT-0400 (EDT)", so here the timezone part is in the format I want. So it might be possible. Maybe the best solution is to just use a regex to grab the timezone off d.toString()...
3) Extra credit: is the format the server requires some sort of standard?
Update: using match(/^.*GMT(-?\d*)/) returns "-0400" at index 1 of the array. Perhaps I should just use that? Im wondering if that regex will work for all timezones in the context of the sign.
Try this code:
var d=new Date(Date.now()); // sets your date to variable d
function repeat(str,count) { // EXTENSION
return new Array(count+1).join(str);
};
function padLeft(str,length,char) { // EXTENSION
return length<=str.length ? str.substr(0,length) : repeat(String(char||" ").substr(0,1),length-str.length)+str;
};
var str=padLeft(String(d.getFullYear()),4,"0")+"-"+
padLeft(String(d.getMonth()),2,"0")+"-"+
padLeft(String(d.getDate()),2,"0")+"T"+
padLeft(String(d.getHours()),2,"0")+":"+
padLeft(String(d.getMinutes()),2,"0")+":"+
padLeft(String(d.getSeconds()),2,"0")+"."+
d.getMilliseconds();
//str+=" GMT";
var o=d.getTimezoneOffset(),s=o<0?"+":"-",h,m;
h=Math.floor(Math.abs(o)/60);
m=Math.abs(o)-h*60;
str+=" "+s+padLeft(String(h),2,"0")+padLeft(String(m),2,"0");
alert(str);
You might want to use one of the date/time formatting libraries that bakes in support for this timezone format (such as http://jacwright.com/projects/javascript/date_format/). In any case, you're right: there really is no good way to control the format output.
As far as the regex goes I don't know that all browsers consistently use the GMT string format, so that may not be the best path forward.

javascript date manipulation

I have a string
2010-08-02 12:13:06.0
and need to get something like
Fri Aug 6 2010
out of it (the input does not map to the output for the values I gave, just examples)
I fear Im going to have to do some string manipulation to get what I want; the js Date object does not seem to have methods capable of parsing the input string.
Is this correct?
We are using jquery, but cant find anything in that library that would help...
Everything has been invented before us:
http://www.mattkruse.com/javascript/date/
You can use the date object for this. Just parse the first part of the date string to get the individual numbers and use setFullYear(), setMonth(), setDate(). You will have to subtract 1 from the month, but then use the toDateString() and it outputs it like your example. http://www.w3schools.com/jsref/jsref_obj_date.asp

Java date format to JavaScript date format

I would like to be able to convert a Java date format string, e.g. dd/MM/yyyy (07/06/2009) to a JavaScript date format string, e.g. dd/mm/yy (07/06/2009).
Has anyone done this before, or got any idea where I might find some code that already does this?
Edit:
Thanks for all the replies but now I realize my mistake and possibly why so many of you were struggling to understand the question; JavaScript doesn't have a built in date formatting ability. I am using the jQuery UI datepicker and I have been setting its date format, assuming it would be calling a standard JS function at some point, not using its own library! When I googled for formatting strings I jumped straight to the tables of what letters could be used, skipping the bit at the beginning explaining how to use the script.
Anyway I'll have to go ahead and possibly write my own I guess, converting a Java date format string into a jQuery date format string (or as close as possible) - I am working on the i18n of our product and have created a java class that stores the preferred date format string used throughout the application, my intention was to also have the ability to supply any jsps with the format string that is equivalent in JS.
Thanks anyway.
If you just need to pass a date from Java to JavaScript, the best way to do it, I think, would be to convert the Java date to milliseconds using date.getTime(), create a JavaScript date initialized with this milliseconds value with new Date(milliseconds)and then format the date with the means of the JavaScript Date object, like: date.toLocaleString().
You could use my plugin jquery-dateFormat.
// Text
$.format.date("2009-12-18 10:54:50.546", "dd/MM/yyyy");
// HTML Object
$.format.date($("#spanDate").text(), "dd/MM/yyyy");
// Scriptlet
$.format.date("<%=java.util.Date().toString()%>", "dd/MM/yyyy");
// JSON
var obj = ajaxRequest();
$.format.date(obj.date, "dd/MM/yyyy");
A similar topic has been answered here:
Converting dates in JavaScript
I personally have found this to be a rather large pain and took the author's suggestion and used a library. As noted, jQuery datepicker has one that is a viable solution if you can afford the overhead of download for your application or already using it.
Check out moment.js! It's "A lightweight javascript date library for parsing, manipulating, and formatting dates". It is a really powerful little library.
Here's an example...
var today = moment(new Date());
today.format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:32 PM"
// in one line...
moment().format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:32 PM"
Here's another example...
var a = moment([2012, 2, 12, 15, 25, 50, 125]);
a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, March 12th 2012, 3:25:50 pm"
a.format("ddd, hA"); // "Mon, 3PM"
a.format("D/M/YYYY"); // "12/3/2012"
Also, its worth mentioning to checkout date.js. I think the two libraries complement each other.
This JavaScript library should be able to help you.
http://plugins.jquery.com/project/fIsForFormat
(I don't know why they have it as a jQuery Plugin, because it works standalone.)
You'd simply split the original formatted date into its individual elements and then create a new Date Object with those elements. Then, use this library's "Date.f()" method to output it into any format you could want.
For example:
var dateOld = "11/27/2010",
dateArr = date1.split("/"),
dateObj = new Date(dateArr[2], dateArr[0], dateArr[1]),
dateNew = dateObj.f("MMM d, yyyy");
document.write("Old Format: " + dateOld + "<br/>New Format: " + dateNew);
This works fine for me:
<%
Date date = Calendar.getInstance().getTime();
%>
<script>
var d = new Date(<%=date.getTime()%>);
alert(d);
</script>
I suggest you the MomentJS with this Plugin that allow you to convert a Java pattern to a JS pattern (MomentJS)
On Java Side
I recommend passing an Instant string which conforms to ISO 8601 standard.
import java.time.Instant;
class Main {
public static void main(String[] args) {
Instant instant = Instant.now();
// You can pass the following string to JavaScript
String strInstant = instant.toString();
System.out.println(strInstant);
// If the number of milliseconds from epoch is required
long millis = instant.toEpochMilli();
System.out.println(millis);
}
}
Output from a sample run:
2022-12-31T09:40:52.280726Z
1672479652280
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
On JavaScript Side
Now, you can parse the ISO 8601 string on the JavaScript side simply by passing it as a parameter to Date constructor. You can also instantiate the Date object with the number of milliseconds from the epoch.
var date = new Date("2022-12-31T09:40:52.280726Z");
console.log(date.toISOString());
// Or if the number of milliseconds from epoch has been received
date = new Date(1672479652280);
console.log(date.toISOString());
The javascript code in this page implements some date functions and they "use the same format strings as the java.text.SimpleDateFormat class, with a few minor exceptions". It is not the very same as you want but it can be a good start point.
If you just want to format dates my date extensions will do that well - it also parses data formats and does a lot of date math/compares as well:
DP_DateExtensions Library
Not sure if it'll help, but I've found it invaluable in several projects.
If you are using java, take a look at the Simple Date Format class.

Categories

Resources