Convert DateTime to Local Timezone - Sugarcrm Moment js - javascript

I am trying to change a specific datetime to user/local timezone datetime. But i couldnt able to convert it. I tried all possible solutions availabe for javascript and tried moment js. It still give me invalid date.
My DateTime Object:
{date: "2017-07-14 14:23:30.000000", timezone_type: 3, timezone: "UTC"}
What I am trying is to convert it to the user timezone or local timezone.
Is there any options available in Moment.js to do it?
In my SugarCRM JavaScript, I couldnt use Date.toUTC.
Methods I tried:
Convert UTC date time to local date time using JavaScript

// input data
var myDateTime = {
date: "2017-07-14 14:23:30.000000",
timezone_type: 3,
timezone: "UTC"
};
// Z in string and format in order to force UTC
var utcMoment = moment(myDateTime.date + "Z", "YYYY-MM-DD HH:mm:ss.SZ");
// convert to time zone of sugar user
var myDate = SUGAR.App.date.UTCtoLocalTime(utcMoment);
// format output
var localDateTime = myDate.format("YYYY-MM-DD HH:mm:ss");
Result:
localDateTime
"2017-07-14 16:23:30"

Found the solution with the help of #jay, did a few modifications and made it work for me.
var myDateTime = {
date: "2017-07-14 14:23:30.000000",
timezone_type: 3,
timezone: "UTC"
};
var myDate = SUGAR.App.date.UTCtoLocalTime(new Date(myDateTime.date));
// 2017-07-14 12:20:26
var resultDate = moment(myDate).format('YYYY-MM-DD HH:mm:ss');
// Mon, Jul 17, 2017 10:40 AM
var resultformat = moment(myDate).format('llll');

Related

Format Date based on Browser time zone (VueJs/JS)

I have a Date in string Format: 2020-07-13 7:07 AM (which is indian time). I need to change this time based on browser time zone which can be either in US or Africa.
I have tried following ways, but i am not able to convert it correctly.
Attaching my steps:
var d = "2020-07-13 7:07 AM";
var date = new Date(d); //Mon Jul 13 2020 07:07:00 GMT+0530 (India StandardTime)
var date1 = moment(date, 'YYYY-MM-DD HH:mm T'); //undefined
Please help me out. I havee to this in both VueJs and Javascript
You should convert your timestamps to an ISO 8601 format including the UTC-offset. This can be done for instance using new Date().toISOString(). Then you can feed the timestamp into moment or, if you want to display the time for a different timezone, have a look at moment-timezone
I figure out the answer in this way:
var buildDate = "2020-07-13_7:07";
let releaseDate = buildDate .split('_');
let date = moment(date);
let newDate = moment(new Date(date.get('year'), date.get('month'), date.get('date'), date.get('hour'), date.get('minute'))).add(new Date().getTimezoneOffset()*-1, 'm').toDate();
let result = moment(newDate).format('MMM DD YYYY h:mm A');

UNIX timestamp of date on midnight UTC+0

I have the following date: 07/08/2018 in the format m/d/Y. This date is july 08, 2018.
And I have the following JavaScript code:
var dateFrom = '07/08/2018';
dateFrom = new Date(dateFrom);
alert(dateFrom);
When I do this, I get the following result:
Sun Jul 08 2018 00:00:00 GMT+0200 (Midden-Europese zomertijd)
As you can see, because I live in Belgium, I get the time + GMT+2. But that's not what I want. I want the exact UNIX timestamp of 07/08/2018 (or any other date) of GMT+0.
I have the following JavaScript code:
var dateFrom = '07/08/2018';
dateFrom = Math.floor((new Date(dateFrom)).getTime()/1000);
alert(dateFrom);
If I execute this code, I get the following result:
1531000800
But that's not what I want. If I check the UNIX timestamp I get (1531000800) on this (https://www.unixtimestamp.com/index.php) website, I get the following result:
1531000800
Is equivalent to:
07/07/2018 # 10:00pm (UTC)
I want the UNIX timestamp that is equal to 07/08/2018 # 00:00am (UTC).
How can I achieve this?
Thanks in advance!
As per the MDM documentation:
The following statement creates a Date object using UTC instead of local time:
var utcDate = new Date(Date.UTC(2018, 11, 1, 0, 0, 0));
Code Sample:
var date = new Date()
var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()))
console.log(date)
console.log(utcDate)

UTC date convert to local timezone

I have a date in UTC format.
"2016-10-12 05:03:51"
I made a function to convert UTC date to my local time.
function FormatDate(date)
{
var arr = date.split(/[- :T]/), // from your example var date = "2012-11-14T06:57:36+0000";
date = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], 00);
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
My Local timezone is GMT +0530.
My code produced this output:
Tue Oct 11 2016 10:33:00 GMT+0530 (IST)
I converted the date with an online tool to get the correct date and time.
Wednesday, October 12, 2016 10:30 AM
My code matches the online tool on time but not on date.
How can I correct my code's output, preferably using moment.js?
UTC is a standard, not a format. I assume you mean your strings use a zero offset, i.e. "2016-10-12 05:03:51" is "2016-10-12 05:03:51+0000"
You are on the right track when parsing the string, but you can use UTC methods to to stop the host from adjusting the values for the system offset when creating the date.
function parseDateUTC(s){
var arr = s.split(/\D/);
return new Date(Date.UTC(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]));
}
console.log(parseDateUTC('2016-10-12 05:03:51').toLocaleString());
If you want to use moment.js, you can do something like the following. It forces moment to use UTC when parsing the string, then local to write it to output:
var d = moment.utc('2016-10-12 05:03:51','YYYY-MM-DD HH:mm:ss');
console.log(d.local().format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.0/moment.js"></script>
Since you have tagged moment, I'm assuming you are using moment.
In such cases, you should keep your approach consistent and not mix moment and date object.
var dateStr = '2016-10-12 05:03:51';
var timeZone = "+0530";
var date = moment.utc(dateStr).utcOffset(dateStr + timeZone)
console.log(date.toString())

Json Stringify date produces a wrong date compared to javascript date

When i create a javascript date and then stringify it and send it to the server, i get two different dates. The stringified date is always one day behind.
So currently i increment my javascript date by 1 day so that i receive the same date on the server.
my current code:
var dt = $(.datepicker).datepicker('getDate');//Fri Aug 26 2016 00:00:00 GMT+0200 (South Africa Standard Time)
var result = Json.stringify(dt); //"2016-08-25T22:00:00.000Z"
Is this the correct approach or am i missing something?
This is due to the timezone component in the Date. The work around I did was:
var date = $(.datepicker).datepicker('getDate');
var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes()))
var result = Json.stringify(utcDate);
The removes the timezone component.
You don't seem to understand that both of your datetimes are actually the same and are correct. You haven't explained why you think that you need to manually alter the one sent to the server. Here is an example that demonstrates that they are in fact the same, just displayed in different formats in different timezones.
// Values from the local datetime string
var local = {
year: 2016,
month: 7,
day: 26,
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 0
};
// Values from the UTC ISO 8601 datetime string
var utc = {
year: 2016,
month: 7,
day: 25,
hours: 22,
minutes: 0,
seconds: 0,
milliseconds: 0
};
// Create Date object as local
var date1 = new Date(
local.year,
local.month,
local.day,
local.hours,
local.minutes,
local.seconds,
local.milliseconds
);
// Create Date object as local from UTC
var date2 = new Date(Date.UTC(
utc.year,
utc.month,
utc.day,
utc.hours,
utc.minutes,
utc.seconds,
utc.milliseconds
));
var pre = document.getElementById('out');
// Display Date1 as local
pre.appendChild(document.createTextNode(date1.toString() + '\n'));
// Display Date2 as local
pre.appendChild(document.createTextNode(date2.toString() + '\n'));
// Display Date2 as UTC
pre.appendChild(document.createTextNode(date2.toUTCString() + '\n'));
// Test if Date1 and Date2 display the same datetime
pre.appendChild(document.createTextNode(
'Date1 === Date2: ' + (date1.getTime() === date2.getTime())
));
<pre id="out"></pre>
JSON converts Date objects to ISO 8601 (by specification), but let's see what happens if you use the solution that you chose.
// Values from the local datetime string
var local = {
year: 2016,
month: 7,
day: 26,
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 0
};
// Create Date object as local
var date = new Date(
local.year,
local.month,
local.day,
local.hours,
local.minutes,
local.seconds,
local.milliseconds
);
// Your solution
var utcDate = new Date(Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes()));
var pre = document.getElementById('out');
// Display Date as local format
pre.appendChild(document.createTextNode(date.toString() + '\n'));
// Display utcDate as local format
pre.appendChild(document.createTextNode(utcDate.toString() + '\n'));
// Test if Date and utcDate display the same datetime
pre.appendChild(document.createTextNode(
'Date1 === Date2: ' + (date.getTime() === utcDate.getTime())
));
<pre id="out"></pre>
You end up with 2 dates that are no longer the same. Don't like ISO 8601 for transmission and storage of datetimes? Well the alternative would be to use the number of milliseconds UTC since the epoch (getTime). You can't make JSON do this conversion instead of ISO 8601, not even using a replacer function. So any conversion would be necessary before using JSON.stringify. So you really need to explain what it is you are trying to achieve and why you think what you have now is incorrect.
Use this
var result = Json.stringify(dt.toISOString());

How To Convert String ' dd/mm/yy hh:MM:ss ' to Date in javascript?

I have Done this
var d='dd/mm/yy hh:MM:ss';
var d1=d.split(" ");
var date=d1[0].split("/");
var time=d1[1].split(":");
var dd=date[0];
var mm=date[1]-1;
var yy=date[2];
var hh=time[0];
var min=time[1];
var ss=time[2];
var fromdt= new Date("20"+yy,mm-1,dd,hh,min,ss);
Is there Any way to do it using JQuery OR JavaScript?
If you are looking for alternatives in jquery or Javascript , then you can go with Moment.js,where you can Parse, Validate, Manipulate, and Display dates in JavaScript.
example:
var date= moment("06/06/2015 11:11:11").format('DD-MMM-YYYY');
This will work regardless of timezone for the format dd/mm/yyy hh:mm:ss only. It also does not rely on third party packages:
let dtStr = "12/03/2010 09:55:35"
console.log(strToDate(dtStr)); // Fri Mar 12 2010 09:55:35
function strToDate(dtStr) {
if (!dtStr) return null
let dateParts = dtStr.split("/");
let timeParts = dateParts[2].split(" ")[1].split(":");
dateParts[2] = dateParts[2].split(" ")[0];
// month is 0-based, that's why we need dataParts[1] - 1
return dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0], timeParts[0], timeParts[1], timeParts[2]);
}
How about Date.parse()?
new Date( Date.parse("05/12/05 11:11:11") );
// Thu May 12 2005 11:11:11 GMT+0200 (CEST)
The output produced is in local timezone and will differ in browsers in different timezones.
We can convert any local date format to datetime datatype using moment js.
Syntax:
moment('<local date value>','<local date format>').format('<expected convert format>')
Example:
moment('26/05/1986 00:00', 'DD/MM/YYYY HH:mm').format("MM/DD/YYYY HH:mm");
then the output will be 05/26/1986 00:00
Cheers
Date#parse should be able to parse that if you split on a string. Id also recommend looking into the npm package moment for date manipulation
From your code it seems that you are trying to convert string into date and also you are trying to fetch previous month. If yes then you can reconstruct your code as below:
Date.prototype.SubtractMonth = function(numberOfMonths) {
var d = this;
d.setMonth(d.getMonth() - numberOfMonths);
return d;
}
$(document).ready(function() {
var dateString='2015-06-17T18:30:12';
var d = new Date(dateString);
alert(d.SubtractMonth(1));
});

Categories

Resources