I have a regular date i.e.:
date= 03-12-2014
I need to convert it to JSON or .Net date format. Like this:
"\/Date(1283219926108)\/"
I can see a lot of posts that go from JSON date to regular date but not backward. Please let me know how to do it. I am hoping for some easy JavaScript way to do it.
Do you know/Have you tried (new Date).getTime()
That's the most easiest "cross-browser" solution I know of ...
In your situation something like:
(new Date(date)).getTime()
It's a little bit vague to see what the difference is between .net- and javascript code.
Can you point it out more clearly?
Take a look at this little jQuery file. https://gist.github.com/gigi81/1868478
It does date parsing for .NET.
I'm trying to use MomentJS to support dates handling in my application. However, I'm facing a problem with date manipulation.
The files are loaded in this order:
<script src="/javascripts/modules/moment/moment.min.js"></script>
<script src="/javascripts/modules/moment/moment-timezone.min.js"></script>
<script src="/javascripts/modules/moment/moment-timezone-data.js"></script>
<script src="/javascripts/modules/moment/moment-with-langs.min.js"></script>
Now in somepart of my JS code I change the moment language to FR or PT.
moment.lang('fr');
Both languages validade a date as "DD/MM/YYYY" instead of american pattern. So I expect moment
to validate a date following the country date pattern passed.
Then 12/10/2014 must be: day (12), month (09), year (2014), but it is returning always american pattern instead of the correct one.
I'm getting the date properties as:
console.log("DAY: " + moment(textDate).date());
console.log("MONTH: " + moment(textDate).month());
console.log("YEAR: " + moment(textDate).year());
where textDate is my date taken from a text input.
## EDIT ##
I know I can pass the pattern to Moment. I.e:
moment(textDate, 'DD/MM/YYYY');
In the case of my application I'm using like this:
moment(textDate, '<%=lingua.general.time.pDate%>');
However, it suppose to work automatically, don't it? Of course if you already have needed language packages as well. So the previous way I mentioned before should Works, whatever.
If you don't pass any formatting arguments, moment will let your browser do the parsing (with the exception of a full ISO timestamp).
To tell moment to do the parsing, and to use the localized short date format associated with the language, pass an L as the format string:
moment(textDate, 'L')
See in the docs:
Parsing using #String+Format
The display formats. Scroll down to "Localized formats". (The parser uses the same format strings)
Also, not related to your question, but moment-with-langs already includes a copy of moment.js, so you don't need both scripts.
I am trying to parse a date string i get from php through ajax call(which is irrelevant for now) using new Date().
however i keep getting wrong results.
My string is 2013-05-09 20:56:17
When i do
var something = new Date("2013-05-09 20:56:17");
alert(something.getMonth());
It keeps alerting 0
In my opinion for some reason new date cant parse this string.
Is there a way to specify the date format for new Date() in JS ?
My current solution is to import php's: date() and strtotime() and use them :
alert(date('m', strtotime("2013-05-09 20:56:17")));
This works however I have to use external js lib and I am pretty sure there is a better JS way to achieve that.
If you use slashes instead of hyphens, it works:
var something = new Date("2013/05/09 20:56:17");
alert(something.getMonth());
It's easy enough to replace any hyphens in a string with slashes first if you need to (say, if you were getting the date string from somewhere else):
var something = new Date("2013-05-09 20:56:17");
something = something.replace('-', '/');
It seems JavaScript's Date constructor doesn't recognize date formats with hyphens, or at least not that particular format.
Choose a different format specifier in PHP for your ajax dates. The format you expect and the format expected by the javascript are different.
var something = new Date("2013-05-09T20:56:17");
Note the 'T' which appears as a literal separator and marks the beginning of time per ISO 8601
Reference for various [browser] javascript date formats
W3 DateTime
Microsoft IE DateTime
Mozilla [Firefox] DateTime
Google DateJs
And lastly, the PHP date format specifier list:
PHP Date
PHP DateTime
Note the 'DATE_ISO8601'; but I suggest not using that at this time. Instead use 'DATE_ATOM' which may produce a date format more widely supported (comments suggest it makes iPhones happier and no issues with other browsers).
To use it in PHP:
$something = new DateTime('NOW');
echo $something->format('c');
echo $something->format(DateTime::ATOM);
I allow users to enter datetime in whatever format they like as long as Ruby's Time.parse method can handle it. Now I need to compare these datetimes in javascript. Is there anything equivalent to Ruby's Time.parse method for javascript?
I need something that can parse for instance "October 13 2012 at 8:15am". I tried datejs but it couldn't handle the "at" word. I would really prefer something that only requires a single function call.
The JavaScript language is picky (and implementations vary) regarding what date format it accepts, so there's no hope without using a library.
Date.js is easily your best bet; however, as you point out, there are sure to be formats that make perfect sense to users but that the library couldn't anticipate.
To workaround, I suggest that you wrap the Date.js parser in a custom scrubbing function that you must maintain:
// using Date.js
function parseDate(str) {
var wordsToRemove = ['on', 'at'] // ...
, regex = new RegExp('\\b(' + wordsToRemove.join('|') + ')\\b', 'g');
return Date.parse(str.replace(regex, ''));
}
Datejs has a really impressive stuff to work with dates in javascript
Try http://momentjs.com/, best time library ever!
This is a bit late, but hopefully it will still help:
If you're only parsing US locale date strings, check out Sherlock.js.
The only limitation is that it doesn't support specifying years or past dates. It can parse 'October 13 2012 at 8:15am' but it will return a Date object for October 13, 2013 at 8:15am, since it always looks forward. You could write some RegEx, like /\b20\d\d\b/ to parse out the year from the string yourself though if needed.
Disclosure: I am the creator of Sherlock.js
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.