I want to compare these Strings2013-11-04 13:10:22.0, 2013-11-04 13:08:03.0 through JavaScript, jQuery or any other library. Is there any way to convert these Strings into Date Type?
I searched this in google and Stack Overflow and found that JavaScript is not good at DateTime formats.
Actually I get JSON data from Server through jQuery.Ajax, My JSON object looks like this
{"RecieverEmail": "email#gmail.com",
"Message": "Hello Ankit",
"DateTime": "2013-11-04 13:08:03.0"
}
and when I parse this Date format using Date.parse method
var d = Date.parse(data.DateTime);
alert(d);
it alerts 1383550683000
Moment.js is a great library for this: http://momentjs.com/
You can pass that exact string in and format it the way you want or call .toDate()on it to get a JavaScript date object.
Parse like this
var d = new Date(data.DateTime);
alert(d);
because the Date.parse() method parses a string representation of a date, and
returns the number of milliseconds
Please use "Momment.js" . It is the free version and it is very simple to handle this type of operation.
http://momentjs.com/
Let the Date be "2013-11-04" make it to a Date Object as
var d=new Date(Date.parse("2013-11-04"));
for compare you can use this number because Date.parse return the number of milliseconds since January 1, 1970, 00:00:00 UTC.
Try this
var d = Date.parse(data.DateTime);
var realDate = new Date(d);
alert(realDate);
There are quite a few good jQuery plugins out there that make dealing with dates a little bit easier. I would also recommend Moment.js since it is the easier to use and more flexible in my opinion.
Here is a fiddle that converts your json datetime into a date object
http://jsfiddle.net/kLMMg/1/
Its as simple as:
var a = {"RecieverEmail": "email#gmail.com",
"Message": "Hello Ankit",
"DateTime": "2013-11-04 13:08:03.0"
}
alert(new Date(a.DateTime))
Related
I want to manipulate date which come from the api.
When I use: console.log(dataAPI.dateStation)
I see 2023-01-24T06:00:00.000Z
Is there way to change the date time in this format 2023-01-24 06:00:00
Just I want to remove T character between date and time and remove .000Z at the end.
The simplest way to do it is probably:
new Date(dataAPI.dateStation).toLocaleString()
If what you want is to display it somewhere, it'll automatically adapt the ISO date you have into a localized and readable date (based on timezone and language).
To know more about it and the options, here is the doc: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
If you want to print the date in ISO 8601 format, you can use the 'sv' (Sweden) locale and Date.toLocaleString().
You can also specify whichever IANA timezone you wish to use, I'm using UTC in this case.
const d = '2023-01-24T06:00:00.000Z'
let timestamp = new Date(d).toLocaleString('sv', { timeZone: 'UTC' });
console.log('Timestamp:', timestamp);
Use the javascript date class with toLocaleString
new Date(dataAPI.dateStation).toLocaleString('en-US');
Without installing some third-party library, your best bet is probably to use the string you have (which is the format returned by toISOString() ),and modify it as desired. If it's already a string in the format you gave, you can just call replace on it:
dataAPI.dateStation.replace('T',' ').replace('.00Z','')
If it's a Date object, first call toISOString() to get a string:
dataAPI.dateStation.toISOString().replace('T',' ').replace('.00Z','')
If it's a string in a possibly-different format, call new Date() to get a Date object, then call toISOString() on that, and finally call replace on the result:
new Date(dataAPI.dateStation).toISOString().replace('T',' ').replace('.00Z','')
You can use regular expressions to remove the parts you don't want:
let s = "2023-01-24T06:00:00.000Z"
s = s.replace(/T/, ' ')
s = s.replace(/\.\d{3}Z$/, '')
console.log(s)
I am looking for a way to get minutes only from a date in string (coming from toISOString).
When using Date object, I was using getTime(), but dont think there is a direct method available for ISO format.
Would I need to extract strings directly from ISO format, as its just a string?
Code:
var depTime = new Date(1222332000).toISOString();
This gives me "1970-01-15T03:32:12.000Z", so what is a good way to get minutes which is "32".
You can use getMinutes() from the date object:
var d = new Date('1970-01-15T03:32:12.000Z');
console.log(d.getMinutes());
This is the right method, but, if there are issues with the Time Zone, you can parse the string:
var depTime = new Date(1222332000).toISOString();
console.log(depTime.split(":")[1]); // 32
You can use
deptime.getMinutes(); // 32
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMinutes
Since it's just a string, regex should work just fine.
T\d+:(\d+)
How could I convert the string "2015-02-02" to ISODate 2015-02-02T00:00:00.000Z? I was trying to find some example but did not.
You can use the regular Javascript date functionality for this
new Date(dateString).toISOString()
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
However, date parsing is very inconsistent across browsers so if you need this to be robust I would look into parsing using for example with Moment.js as this will allow you to specify a format string by which the date should be parsed like such
date = moment("12-25-1995", "YYYY-MM-DD");
date.format(); //will return an ISO representation of the date
from: http://momentjs.com/docs/#/parsing/string/
To change "2015-02-02" to "2015-02-02T00:00:00.000Z" simply append "T00:00:00.000Z":
console.log('2015-02-02' + 'T00:00:00.000Z');
Parsing to a Date and calling toISOString will fail in browsers that don't correctly parse ISO dates and those that don't have toISOString.
new Date("2015-02-02").toISOString()
new Date("11/11/2019").toISOString()
or use it as a variable
mydate = "11/11/2019"
new Date(mydate).toISOString()
I have a system that returns a JSON object that contains dates in string format.
These dates are in the format "2012-10-19 06:05:38 GMT" (no... I'm stuck with them like this)
So I need to get this into a date object (d) ready to output as d.toLocaleDateString()
In chrome it works perfectly by just passing the string to a new Date (Bad bad Chrome - makes Eric lazy), but of course it fails in FF and IE
I can fix it by splitting the string but its not pretty and I've not figured out dealing with the offsets from GMT.
There must be a more elegant way...?
I'm sure someone here can do it in one line.
It's not quite a one-liner, but if you know all your dates will be GMT, something like the following should work:
function parseDate(dateString) {
// [y, m, d, hr, min, sec]
var parts = dateString.match(/\d+/g);
// Months are 0-indexed
parts[1] -= 1;
return new Date(Date.UTC.apply(Date, parts));
}
If I were you, and had access to the serverside script gathering that information (and outputting it) I would convert the date into a unix timestamp, and then make Javascript process that using the Date constructor easily.
EDIT: You can use strtotime() function to convert the string date into numeric unix timestamp if you're using PHP.
If you know the exact format, you could use a library such as Moment.js: Documentation for Moment.js.
To parse:
var dateString = "2012-10-19 06:05:38 GMT".replace(" GMT", "");
var date = moment(dateString, "YYYY-MM-DD HH:mm:ss");
You can just parse the dateString manually,and pass the Date the Date constructor exactly:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
var dateString = "2012-10-19 06:05:38 GMT".split(" "),
date = dateString[0].split("-"),
time = dateString[1].split(":");
var dateObj = new Date(date[0],date[1]-1,date[2],time[0],time[1],time[2]);
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.