I have a time stamp of the in following form
2013-05-05 16:00:00
Can anyone tell me how to get rid of the time part and advance it one day using javascript, so I have.
2013-05-06
var date1 = new Date("2013-05-06 16:00:00");
var date2 = new Date(date1.getFullYear(),date1.getMonth(),date1.getDate()+1)
Ok well make the time stamp a string and use the .split() method on the space that separates the date and time take a look here for more information: http://www.w3schools.com/jsref/jsref_split.asp
Or more appropriately use the requisite date function like new Date(year,month,day); http://www.w3schools.com/jsref/jsref_obj_date.asp
Related
Using Moment.js I can't transform a correct moment object to a date object with timezones. I can't get the correct date.
Example:
var oldDate = new Date(),
momentObj = moment(oldDate).tz("MST7MDT"),
newDate = momentObj.toDate();
console.log("start date " + oldDate)
console.log("Format from moment with offset " + momentObj.format())
console.log("Format from moment without offset " + momentObj.utc().format())
console.log("(Date object) Time with offset " + newDate)
console.log("(Date object) Time without offset "+ moment.utc(newDate).toDate())
Use this to transform a moment object into a date object:
From http://momentjs.com/docs/#/displaying/as-javascript-date/
moment().toDate();
Yields:
Tue Nov 04 2014 14:04:01 GMT-0600 (CST)
As long as you have initialized moment-timezone with the data for the zones you want, your code works as expected.
You are correctly converting the moment to the time zone, which is reflected in the second line of output from momentObj.format().
Switching to UTC doesn't just drop the offset, it changes back to the UTC time zone. If you're going to do that, you don't need the original .tz() call at all. You could just do moment.utc().
Perhaps you are just trying to change the output format string? If so, just specify the parameters you want to the format method:
momentObj.format("YYYY-MM-DD HH:mm:ss")
Regarding the last to lines of your code - when you go back to a Date object using toDate(), you are giving up the behavior of moment.js and going back to JavaScript's behavior. A JavaScript Date object will always be printed in the local time zone of the computer it's running on. There's nothing moment.js can do about that.
A couple of other little things:
While the moment constructor can take a Date, it is usually best to not use one. For "now", don't use moment(new Date()). Instead, just use moment(). Both will work but it's unnecessarily redundant. If you are parsing from a string, pass that string directly into moment. Don't try to parse it to a Date first. You will find moment's parser to be much more reliable.
Time Zones like MST7MDT are there for backwards compatibility reasons. They stem from POSIX style time zones, and only a few of them are in the TZDB data. Unless absolutely necessary, you should use a key such as America/Denver.
.toDate did not really work for me, So, Here is what i did :
futureStartAtDate = new Date(moment().locale("en").add(1, 'd').format("MMM DD, YYYY HH:MM"))
hope this helps
Since momentjs has no control over javascript date object I found a work around to this.
const currentTime = new Date();
const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss");
const convertTimeObject = new Date(convertTime);
This will give you a javascript date object with the converted time
The question is a little obscure. I ll do my best to explain this. First you should understand how to use moment-timezone. According to this answer here TypeError: moment().tz is not a function, you have to import moment from moment-timezone instead of the default moment (ofcourse you will have to npm install moment-timezone first!). For the sake of clarity,
const moment=require('moment-timezone')//import from moment-timezone
Now in order to use the timezone feature, use moment.tz("date_string/moment()","time_zone") (visit https://momentjs.com/timezone/ for more details). This function will return a moment object with a particular time zone. For the sake of clarity,
var newYork= moment.tz("2014-06-01 12:00", "America/New_York");/*this code will consider NewYork as the timezone.*/
Now when you try to convert newYork (the moment object) with moment's toDate() (ISO 8601 format conversion) you will get the time of Greenwich,UK. For more details, go through this article https://www.nhc.noaa.gov/aboututc.shtml, about UTC. However if you just want your local time in this format (New York time, according to this example), just add the method .utc(true) ,with the arg true, to your moment object. For the sake of clarity,
newYork.toDate()//will give you the Greenwich ,UK, time.
newYork.utc(true).toDate()//will give you the local time. according to the moment.tz method arg we specified above, it is 12:00.you can ofcourse change this by using moment()
In short, moment.tz considers the time zone you specify and compares your local time with the time in Greenwich to give you a result. I hope this was useful.
To convert any date, for example utc:
moment( moment().utc().format( "YYYY-MM-DD HH:mm:ss" )).toDate()
let dateVar = moment('any date value');
let newDateVar = dateVar.utc().format();
nice and clean!!!!
I needed to have timezone information in my date string. I was originally using moment.tz(dateStr, 'America/New_York').toString(); but then I started getting errors about feeding that string back into moment.
I tried the moment.tz(dateStr, 'America/New_York').toDate(); but then I lost timezone information which I needed.
The only solution that returned a usable date string with timezone that could be fed back into moment was moment.tz(dateStr, 'America/New_York').format();
try (without format step)
new Date(moment())
var d = moment.tz("2019-04-15 12:00", "America/New_York");
console.log( new Date(d) );
console.log( new Date(moment()) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
moment has updated the js lib as of 06/2018.
var newYork = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london = newYork.clone().tz("Europe/London");
newYork.format(); // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format(); // 2014-06-01T17:00:00+01:00
if you have freedom to use Angular5+, then better use datePipe feature there than the timezone function here. I have to use moment.js because my project limits to Angular2 only.
new Date(moment()) - could give error while exporting the data column in excel
use
moment.toDate() - doesn't give error or make exported file corrupt
var dt_now = '2-22-2013';//mm-dd-yyyy, this is dynamic in actual code
dt_now = dt_now.split("-");
dt_now = addZero(dt_now[2])+'-'+addZero(dt_now[0])+'-'+addZero(dt_now[1]);
dt_now = new Date(dt_now);
I am using the above code to convert a user defined text to actual date for use in rest of my code. it seems to work ok for me but on another system which is situated in a different timezone(my time -12 hours), the date comes out as February 21st instead of Feb 22nd, that is, it is running one day behind the expected date. I have no idea how to fix this or what the error might be. Any suggestions?
To avoid timezone issues, use UTC. You don't have to rely on a library; simple ISO 8601 date strings would be sufficient. See Date.prototype.toISOString for making one from a Date (compatibility).
Constructing is as simple as new Date('yyyy-mm-ddT00:00Z'), so you just need a minor change to your code to create a Date
var dt_now = '2-22-2013';//mm-dd-yyyy, this is dynamic in actual code
dt_now = dt_now.split("-");
dt_now = addZero(dt_now[2])+'-'+addZero(dt_now[0])+'-'+addZero(dt_now[1])+'T00:00Z';
dt_now = new Date(dt_now);
The Z indicates UTC. I include a time (T00:00) so it matches that which would be generated by toISOString.
In the method that outputs the date you need to use getUTC* instead of get*, i.e. getUTCDate(). To generate a date object with UTC info refer to the second answer in How do you convert a JavaScript date to UTC?
I have a date in this string format "02/28/2012" and I want to convert it to UTC.
I'm using the jquery datepicker to select thedate and populate an inputbox. any clues?
Thanks
var datestr = "07/08/2005";
var datearr = datestr.split("/")
var utc = Date.UTC(datearr[2],datearr[0],datearr[1]);
var utcdate = Date.UTC(2012,2,28);
The other answers are good, but they will give you the wrong result.
In Javascript, the month argument is zero-indexed, so make sure to subtract 1 from the standard month number,
var utcms = Date.UTC(2012,2-1,28);
Unfortunately jquery .datepicker.parseDate(str) injects a local timezone (it would be nice if the documentation said this), and Date(str) and Date.parse(str) appear unpredictable about their treatment of local vs UTC.
I got this problem when dealing with date time conversion. I have timestamp data from postgreSQL database with format like this one
"2011-04-04 19:27:39.92034"
In order to display it in highcharts, I have to convert it to date or time object. Without milliseconds, I easily convert it with Date.js
But milliseconds can't be handled with that library. I tried also with Date.parse but always got NaN.
Any solution for this problem? Thank you
JS built in Date class should be able to handle this, and getTime() can return milliseconds since start 1970 (UNIX time). Watch out for time zone issues though; the constructor may interpret the date/time as being local, but getTime()'s milliseconds since 1970 may be in UTC, baking in a conversion that is difficult to remove.
new Date("2011-04-04 19:27:39.92034").getTime()
1301941659920
Many ways to Rome. The given code will return '(datestr=) 2011-4-4 19:27:39.92'. Is that what you look for?
var darr = '2011-04-04 19:27:39.92034'.split('.')
, dat=new Date(darr[0])
, datestr = '';
dat.setMilliseconds(Math.round(darr[1]/1000));
datestr = [ [dat.getFullYear(),dat.getMonth()+1,dat.getDate()].join('-')
,' ',
[dat.getHours(),dat.getMinutes(),dat.getSeconds()].join(':')
,'.',
dat.getMilliseconds()
].join('');
Can't you just cut of the last 6 chars of that string? You might then round the miliseconds and eventually add a second to you time object.
This is simpler and in one line:
new Date('01/09/2015 06:16:14.123'.split(".")[0])
I want to get the time difference between saved time and current time in javascript or jquery. My saved time looks like Sun Oct 24 15:55:56 GMT+05:30 2010.
The date format code in java looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
How to compare it with the current time and get the difference?
Is there any inbuilt function in jquery or javascript??
Any suggestions or links would be appreciative!!!
Thanks in Advance!
Update
Date is stored as varchar in the DB. I am retriving it to a String variable and then change it to java.util.Date object. The java code looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
This date object was sent to client. There i want to compare the saved date with current date and want to show the time difference like 2 secs ago, 2 hours ago, 2 days ago etc... like exactly in facebook. I have gone through some date to timestamp conversion tutorial in java script and now i can get the difference in timestamp. Now, i want to know how i shall change it to some format like "2 secs or 2 days or 24 hours"??. Or, how i shall change it back to date format???
Convert them into timestamps which are actually integers and can get subtracted from each other. The you just have to convert back the resulting timestamp to a javascript date object.
var diff = new Date();
diff.setTime( time2.getTime()-time1.getTime() );
You dont need to explicit convert, just do this:
var timediff = new Date() - savedTime;
This will return the difference in milliseconds.
jQuery doesn't add anything for working with dates. I'd recommend using Datejs in the event that the standard JavaScript Date API isn't sufficient.
Perhaps you could clarify exactly what input and output you're aiming for. What do you mean by "the difference?" There is more than one way to express the difference between to instants in time (primarily units and output string formatting).
Edit: since you said you're working with jQuery, how about using CuteTime? (Demo page)